爲什麼在您的viewpager中使用兩個不同的ID,當您的方向改變時可以刪除Fragment B?
可以檢索內部onCreateView()或的onResume()這樣的片段(本例中工作的父母片段裏面,但也可以使用一個父活動內像的onResume()):
@Override
public void onResume() {
super.onResume();
// ... initialize components, etc.
pager.setAdapter(pagerAdapter);
List<Fragment> children = getChildFragmentManager().getFragments();
if (children != null) {
pagerAdapter.restoreFragments(children, orientation);
}
}
然後在你的適配器內:
@Override
public void restoreFragments(List<Fragment> fragments, int orientation) {
List<Fragment> fragmentsToAdd = new ArrayList<Fragment>();
Collections.fill(fragmentsToAdd, null);
if (Configuration.ORIENTATION_LANDSCAPE == orientation) {
for (Fragment f : fragments) {
if (!(f instanceof FragmentB)) {
fragmentsToAdd.add(f);
}
}
}
this.fragmentsInAdapter = Arrays.copyOf(temp.toArray(new Fragment[0]), this.fragments.length); // array of all your fragments in your adapter (always refresh them, when config changes, else you have old references in your array!
notifyDataSetChanged(); // notify, to remove FragmentB
}
這應該工作。
Btw。如果您使用Support Library V13,則無法使用FragmentManager.getFragments(),因此您需要通過id或標記來獲取它們。
你嘗試重寫'onSaveInstanceState'和避免調用'super.onSaveInstanceState'該方法。這將防止'Fragment'被保存。 –
這是我當前的解決方法,但是避免調用super.onSaveInstanceState,我清除ViewPager所做的所有狀態。我不認爲這是最好的解決方案,所以我仍然會問,因爲有時會在ViewPager中看到崩潰。 – Wayne