關於FragmentManager findFragmentById 返回nul,findfragmentbyid

來源:互聯網
上載者:User

關於FragmentManager findFragmentById 返回nul,findfragmentbyid

先看Fragment的兩種產生方式

一.用xml標籤產生

在fragment的宿主activity中添加xml標籤

1     <fragment2         android:id="@+id/fragment_newsContent"3         android:name="com.firstcode.section4_news.NewsContentFragment"4         android:layout_width="match_parent"5         android:layout_height="match_parent"/>

name為你建立的fragment類

這種方法在activity建立時fragment已經產生了

在Activity中擷取fragment執行個體的操作:

1         NewsContentFragment fragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.fragment_newsContent);

 

二、用java代碼動態產生

在fragment的宿主activity的視圖檔案中添加FrameLayout進行佔位

1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"2     android:id="@+id/fragmentContainer"/>

在Activity中產生fragment的操作

1 FragmentManager fm = getFragmentManager();2 fm.beginTransaction()3    .add(R.id.fragmentContainer,“你建立的fragment類執行個體”)
.commit();

 

問題分析:

我在使用用FragmentManager.findFragmentById 返回nul的問題就在這,我是通過第二種方式來產生fragment的,也就是說在findFragmentById的實參

我填的是FrameLayout的Id,而非fragment的Id 所以會返回null

解決方案:

  1.如果是靜態產生fragment,擷取fragment執行個體用getFragmentManager().findFragmentById

  2.如果是java代碼動態產生fragment,擷取fragment執行個體直接new 一個就好了 沒必要用getFragmentManager().findFragmentById

  3.注意xml檔案中的標籤FrameLayout與fragment

 

還有個問題,我也是這樣解決的 在fragment視圖裡給textview添加文字

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

原因是通過java代碼產生的fragment add裡的Id參數填的是fragment的id 所以fragment的視圖沒有產生

 

理解兩種fragment產生方式最好的文檔莫過於google官方的Android Training下面是中文翻譯

使用xml標籤添加fragment

使用java代碼動態添加fragment

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.