关于网友提出的“Android使用Fragment,不能得到Fragment内部控件,findViewById结果是Null”问题疑问,本网通过在网上对“Android使用Fragment,不能得到Fragment内部控件,findViewById结果是Null”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题:Android使用Fragment,不能得到Fragment内部控件,findViewById结果是Null
描述:androidfragment
程序非常简单,好长时间没有搞定,郁闷。。。。。。。。。。。。
描述:
一个Activity:MainActivity,内部是一个Fragment:FragmentA,FragmentA里面有TextView。
问题:无论如何也得不到FragmentA内部的TextView,返回值永远是Null
具体描述:
MainActivity的layout:activity_main.xml
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<>
android:id="@+id/fragment_a"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FragmentA的layout:fragment_a.xml
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textSize="18sp"
android:text="初始化文本" />
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
FragmentA.java
public class FragmentA extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// TextView textView1 = (TextView) getView().findViewById(R.id.textView1);
// textView1.setText("改变");
}
具体问题:
在FragmentA.onActivityCreated()中,
TextView textView1 = (TextView) getView().findViewById(R.id.textView1); 得到的始终是Null。
在Fragment.onCreateView()中,
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 第二个参数 container一直是个空值
在MainActivity中,findViewById(R.id.textView1), 同样是空值。
问题在哪里呢??????????
解决方案1: 先Inflate你的fragment布局,然后再用inflate fragment的View调用findViewById()查找
解决方案2: 试试继承FragmentActivity
解决方案3: mView = inflater.inflate(R.layout.ui_listview, null);
用mView查找
解决方案4: 这样就可以了。
public class FragmentA extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
return view ;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView textView1 = (TextView) getView().findViewById(R.id.textView1);
textView1.setText("改变");
}
以上介绍了“Android使用Fragment,不能得到Fragment内部控件,findViewById结果是Null”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/672679.html