我的ViewPager
的一個Fragment
出現奇怪的問題。我有一個ViewPager
三個Fragment
。 一切都運行良好,直到現在。當應用程序啓動時,ViewPager
(與FragmentPagerAdapter
)附加了三個片段,因此我可以導航從一個滑動到另一個沒有任何問題。 問題就來了,當我試圖手動重新啓動應用程序(註銷後)這樣的:重新啓動應用程序時出現「IllegalStateException碎片未附加到活動」
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
現在,當我註銷和應用程序重新啓動應用程序崩潰,並通過IllegalStateException Fragment not attached to Activity
試圖從對資源的訪問進行時片段。
這裏就是我附上fragments
,則adapter
代碼:
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public BaseListFragment getItem(int index) {
switch (index) {
case 0:
case R.id.index_explore:
BaseListFragment fragment0 = new Fragment0();
fragment0.setUserVisibleHint(true);
return fragment0;
case 1:
case R.id.index_main:
if (fragment instanceof FragmentList)
((FragmentList) fragment).removeMap();
return new Fragment1();
case 2:
case R.id.index_my_stuff:
BaseListFragment fragment2 = new Fragment2();
fragment2.setUserVisibleHint(true);
return fragment2;
default:
if (fragment instanceof FragmentList)
((FragmentList) fragment).removeMap();
return new Fragment1();
}
}
@Override
public int getCount() {
return 3;
}
}
然後,我設置:
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAppSectionsPagerAdapter);
這是Fragment0造成死機。 我不明白它爲什麼會發生,因爲它應該重新構建一切(所以帶有片段的適配器),就像應用程序第一次啓動時一樣。 也許有一些我認爲是不正確的? 我以前搜索過一些類似的問題,這個例外有很多相關的問題,但是沒有解決我的問題,我認爲這是一個特例。
後,你所添加的片段 –
我剛剛編輯我的問題的活動代碼。希望能幫助到你。謝謝。我一直在想,問題在於重新啓動,因爲它直到現在都完美運行。也許我重新啓動應用程序的方式不會重新創建活動,因此它不會附加片段,而是使用已保存的已將它們分離的實例?我不知道我是否解釋得很好。 – DroidBeginner
http://stackoverflow.com/a/10941410/1865860也許是有用的 – dentex