我是新来开发Android过程中对片段的和。
我想访问的主要活动我的片段的控制,但“findViewById”返回null。 无片段的代码工作正常。
这里是我的代码部分:
片段 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="HardcodedText" >
<EditText
android:id="@+id/txtXML"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:ems="10"
android:scrollbars="vertical">
</EditText>
</LinearLayout>
MainActivity的OnCreate:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.initialisePaging();
EditText txtXML = (EditText) findViewById(R.id.txtXML);}
在这一点上txtXML为空。
缺少了什么在我的代码或我应该怎么办?
试着这样对onCreateView您的片段
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout ll = (LinearLayout )inflater.inflate(R.layout.tab_frag1_layout, container, false);
EditText txtXML = (EditText) ll.findViewById(R.id.txtXML);
return ll;
}
你应该inflate
的片段布局onCreateView
的方法Fragment
,那么你可以简单地访问它的元素findViewById
你的Activity
。
在本实施例我的片段布局是一个的LinearLayout所以铸inflate
结果的LinearLayout。
public class FrgResults extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//some code
LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
//some code
return ll;
}
}
我迟到了,但对于其他人有这个问题。 你应该在膨胀的onCreateView方法你的看法。 然后重写onCreateActivity
方法,您可以使用getView().findViewById
那里。
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment, container, false);
}
您无法通过访问片段的视图中的活动课findViewById
,而不是你可以做的是...
您必须碎片类的对象在你的活动文件,对不对? 创建该分段类的EditText类的getter方法和访问方法在您的活动。
创建一个回调的片段类在需要的EDITTEXT obj中的事件。
1)试试这个:
Eclipse菜单 - >项目 - >清除...
更新
2)如果你有一个“主”布局2分或更多的情况下,检查是否个个都以“txtXML” ID的观点
3)
片段是一块应用程序的用户界面或行为可以被放置在一个活动。 与片段交互是通过FragmentManager,其可以经由Activity.getFragmentManager()和Fragment.getFragmentManager()来获得完成。
片段类可用于多种方式来实现各种效果。 它是核心,它代表被一个更大的活动内运行的特定操作或接口。 片段是紧密联系在一起的是在活动,并且不能从一个分开使用。 虽然片段定义了自己的生命周期,即周期取决于其活动:如果该活动已停止,它内部没有碎片可以启动; 当活动被销毁,所有片段将被销毁。
研究这个 。 您必须使用FragmentManager。
如果你想为你在活动的onCreate使用使用findViewById,你可以简单地把所有的onActivityCreated overrided方法。