程序很easy。好长时间没有搞定。郁闷。。。。java
。android
。。。。app
。ide
。post
。spa
在论坛咨询,最终找到答案。code
描写叙述:xml
一个Activity:MainActivity。内部是一个Fragment:FragmentA。FragmentA里面有TextView。blog
问题:无论怎样也得不到FragmentA内部的TextView,返回值永远是Null继承
详细描写叙述:
MainActivity的layout:activity_main.xml
<?xml version="1.0" encoding="utf-8"?FragmentA的layout:fragment_a.xml> <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>
<?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="初始化文本" />
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
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("改变"); }
在Fragment.onCreateView()中,
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 第二个參数 container一直是个空值
问题在哪里呢??????????
===============================================================================================================
缘由
让Activity 继承 android.support.v4.app.FragmentActivity, 让Fragment继承android.support.v4.app.Fragment就可以了
这样。在FragmentA的onStart等方法中,getActivity().findViewById(R.id.textView1) 就能获得这个TextView。
直接继承 android.app.Fragment,就不行。或许是Android的bug吧。
事实上我是依照developer.android.com上的trainning的样例作的。那个样例是为了兼容android3.0曾经的系统,继承了android.support.v4.app.Fragment。官方样例执行正常。
个人手机是Android4.1的,可以支持Fragment。因此我直接继承了adnroid.app.Fragment。结果就死活不成功。
想不到是这个缘由。