程序非常简单,好长时间没有搞定,郁闷。。。。。。。。。。。。
描述:
一个Activity:MainActivity,内部是一个Fragment:FragmentA,FragmentA里面有TextView。
问题:无论如何也得不到FragmentA内部的TextView,返回值永远是Null
具体描述:
MainActivity的layout:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.fragmentexercise.FragmentA"
android:id="@+id/fragment_a"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
FragmentA的layout:fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
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), 同样是空值。
问题在哪里呢??????????
------解决方案--------------------
这样就可以了。
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("改变");
}
------解决方案--------------------
mView = inflater.inflate(R.layout.ui_listview, null);
用mView查找
------解决方案--------------------
试试继承FragmentActivity
------解决方案--------------------