1. 程式人生 > >Android使用Fragment,不能得到Fragment內部控件,findViewById()結果是Null--已經解決

Android使用Fragment,不能得到Fragment內部控件,findViewById()結果是Null--已經解決

文本 match ces ear creat 能夠 -s 兼容 mat

程序很easy。好長時間沒有搞定。郁悶。。。。

。。。。

在論壇咨詢,最終找到答案。

描寫敘述:

一個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), 相同是空值。


問題在哪裏呢??????????


===============================================================================================================

原因


讓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。結果就死活不成功。

想不到是這個原因。

Android使用Fragment,不能得到Fragment內部控件,findViewById()結果是Null--已經解決