gpt4 book ai didi

android - 将新适配器分配给我的 ViewPager 时应用程序崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:01 25 4
gpt4 key购买 nike

我有一个 ViewPager,它在应用程序启动时由 FragmentStatePagerAdapter 填充:

    ViewPager mViewPager;

...

@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);

mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new PageAdapter(getChildFragmentManager()));
//PageAdapter extends from FragmentStatePagerAdapter
}

这可以正常工作。

现在,当用户更改应用程序的设置时,我想像这样为 ViewPager 分配一个新的适配器:

@Override
public void updateObserver(SETTING_KEY key)
{
mViewPager.setAdapter(new PageAdapter(getChildFragmentManager()));
Log.d("info", "updating");
}

不幸的是,应用程序在调用 updateObserver 后崩溃,出现以下异常:

01-22 23:22:45.957: E/AndroidRuntime(13131): FATAL EXCEPTION: main 01-22 23:22:45.957: E/AndroidRuntime(13131): java.lang.IllegalStateException: Fragement no longer exists for key f0: index 0 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:575) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1281) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.view.View.dispatchRestoreInstanceState(View.java:13188) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2850) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2856) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.view.View.restoreHierarchyState(View.java:13166) 01-22 23:22:45.957: E/AndroidRuntime(13131): at android.support.v4.app.Fragment.restoreViewState(Fragment.java:425) ...

如何在不使应用程序崩溃的情况下将新适配器分配给 ViewPager

最佳答案

使用 getFragmentManager() 而不是 getChildFragmentManager()。

关于android - 将新适配器分配给我的 ViewPager 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21295391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com