一個片段,我有以下2佈局文件:findFragmentById返回不存在
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:id="@+id/list_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
class="MyListFragment"/>
</LinearLayout>
(w900dp)
<fragment android:id="@+id/list_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".3"
class="MyListFragment"/>
<fragment android:id="@+id/content_fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".7"
class="MyContentFragment"/>
然後在我的活動我有:
public class ReportActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the content fragment
MyContentFragment contentFragment = (MyContentFragment) getSupportFragmentManager().findFragmentById(R.id.content_fragment);
if (contentFragment != null) {
// sometimes I get a handle to this fragment when I should not
contentFragment.updateContent(//some content);
}
}
我的問題是這樣的。當我以橫向模式啓動應用程序時,寬度足以顯示這兩個片段。當我旋轉到縱向時,它不再足夠寬,沒有內容片段的佈局文件被加載。但是,當我調用片段管理器來獲取該片段時,它會找到它。然後當我調用更新內容失敗,因爲該片段內的UI組件不再存在。
爲什麼getFragmentById返回確實存在的片段,但在設備旋轉後不再存在?
謝謝。但是,我不編程創建片段,Android爲我做它,因爲它們在我的佈局文件中。 I.E.我沒有發佈更多活動代碼的原因是因爲沒有更多。當您在xml佈局文件中使用片段標籤時,android會創建/銷燬片段。 – lostintranslation 2015-04-02 21:57:51
你可能想嘗試手動處理它,因爲框架似乎沒有做得很好。 – athingunique 2015-04-02 21:59:22