[英]Fragment on Screen Rotation
我已經將viewpager添加到包含兩個頁面的活動中。
在onCreate of activity中,我將片段添加到fragmentAdapter:
public void onCreate(Bundle savedInstanceState)
{
......
FragmentAdapter fragmentAdapter = new FragmentAdapter
(
getSupportFragmentManager(),
new Fragment[]{FragmentGame.builder(id), FragmentComments.builder(id)},
new String[]{getString(R.string.gameInfo), getString(R.string.comments)}
);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(fragmentAdapter);
public static FragmentGame builder(long id)
{
FragmentGame fragmentGame = new FragmentGame();
// fragmentGame.id = id;
Bundle bundle = new Bundle();
bundle.putLong(Constants.EXTRA_ID, id);
fragmentGame.setArguments(bundle);
return fragmentGame;
}
第一次創建活動時,片段的onCreateView會按預期調用。
奇怪的行為是當屏幕第一次旋轉時, onCreateView of fragment被調用兩次,但第二次調用只有正確的id ,而第一次調用id為0。
在第二個屏幕旋轉時, onCreateView被調用三次,並且只有最后一個具有id。
通過更多屏幕旋轉, onCreateView調用增加。
我發現了一些關於片段和屏幕旋轉的相關問題,但我無法弄清楚為什么會發生這種情況以及如何以正確的方式進行。
-----更新------
當我用直接值設置替換bundle時,ID問題得以解決。
如果您不想在方向更改時重新加載片段,請在清單文件中為要加載片段的活動寫下以下內容。
<activity
android:name="your activity name"
android:configChanges="orientation|screenSize" // add this to your activity
android:label="@string/app_name">
</activity>
每次旋轉設備時,都會創建一個新片段並將其添加到FragmentManager中。
您之前創建的所有片段仍在FragmentManager中,因此每次計數增加1。
如果您希望在片段中保留一個值,則需要將其存儲在參數中,否則當系統重新創建片段時,它包含的任何值都將丟失。
public static FragmentGame builder(long id) {
Bundle args = new Bundle();
args.putInt("id", id);
fragmentGame f = new fragmentGame();
f.setArguments(args);
}
而不是創建一個新的片段,我懷疑你真的想要在旋轉設備時檢索以前創建的片段。 使用getSupportFragmentManager().findFragmentById()
或getSupportFragmentManager().findFragmentByTag()
來執行此操作。
編輯:額外代碼
// Add fragment to the manager
FragmentTransaction trans=getSupportFragmentManager().beginTransaction();
trans.add(f,"myTag");
trans.commit();
// retrieve the fragment
Fragment f= getSupportFragmentManager().findFragmentByTag("myTag");
只是嘗試檢索片段,如果值為null,則創建一個新片段並將其添加到管理器,否則使用檢索到的片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.