2
我想在我的活動中動態地用另一片段替換片段。Android添加沒有交易的片段
它看起來就像你不能代替在佈局文件靜態定義一個片段,有一個動態創建的片段: Android: can't replace one fragment with another
建議的解決方案是動態地添加原始片段的onCreate方法:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ShelfFragment shelves = new ShelfFragment();
ft.add(R.id.left_fragment, shelves);
ft.addToBackStack(null);
ft.commit();
}
這會起作用,但是當用戶按下後退按鈕時,原始碎片被移除而不是關閉活動,因爲FragmentTransaction將其添加到FragmentManager堆棧。
有沒有方法可以在沒有事務/堆棧條目的情況下將初始片段添加到我的活動中?
刪除addToBackStack調用可以工作,但如果您稍後嘗試使用FragmentTransaction.replace替換原始片段,則在點擊後退按鈕時原始片段不會返回。 –