這不是一個答案,但我需要空間來解釋,我在這個問題circeling:
似乎有比更一般的問題只是getActivity()。因爲片段的變量聲明也「消失」爲空。片段的新實例已被「接管」。這發生在當前標籤向多個標籤移動一個以上的情況下。
示例:我定義了5個選項卡。我有一個可以在UI中操作的標籤2。更改2個內容後,我可以在標籤頁之間移動,或者使用標籤點擊或手指掃描。無論哪種方式。
結果?只要我訪問左側或右側的下一個選項卡,然後移回,更改的數據仍然存在於選項卡2上。只要我將兩個或多個選項卡從選項卡2移開然後返回,標籤2始終重置。無論有多少標籤都存在。在這個過程中,我是否擊中最後一個或第一個選項卡並不重要。代碼?它是同在引用的教程,此外:
//add tabs (notice the once only saving of the fragment into profileViewer)
mTabsAdapter.addTab(actionBar.newTab()
//.setText(R.string.action_favorite)
.setIcon(R.drawable.ic_action_favorite),
TabFragmentDemo.class, null);
mTabsAdapter.addTab(actionBar.newTab()
//.setText(R.string.new_profile)
.setIcon(R.drawable.ic_action_add_person),
ProfileViewer.class, null);
profileViewer = (ProfileViewer) mTabsAdapter.getItem(NEW_PROFILE);
mTabsAdapter.addTab(actionBar.newTab()
//.setText(R.string.action_select)
.setIcon(R.drawable.ic_action_view_as_list),
TabFragmentDemo.class, null);
mTabsAdapter.addTab(actionBar.newTab()
//.setText(R.string.action_select)
.setIcon(R.drawable.ic_action_view_as_list),
TabFragmentDemo.class, null);
mTabsAdapter.addTab(actionBar.newTab()
//.setText(R.string.action_select)
.setIcon(R.drawable.ic_action_view_as_list),
TabFragmentDemo.class, null);
那麼簡單dialogFragment選擇一個日期,然後將此日期設置(不利於省略日期選擇器而直接設定一個日期)
public void showDatePickerDialog(View v) {
dateOfBirthPicker = new DateOfBirthPicker();
dateOfBirthPicker.show(fragmentManager, datePickerTag);
}
//the callback from datepicker:
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
//update the fragment
profileViewer.setCardFromDate (this, day, month, year);
注意「this」作爲強制上下文傳遞給片段。這裏最大的問題是爲什麼只要我的代碼中沒有任何內容要求,選項卡就會丟失它的原始片段?
確保你正確地處理了片段。文檔很老,可能還沒有更新,因爲在早期開發階段*(在使用多年以後)。如果你有一個特定的場景,片段的getActivity()返回null,你應該添加一些代碼實現到你的問題,看看發生了什麼。 – Luksprog