android – 在片段中使用FragmentPagerAdapter

我在一些Android代码中做了一些重构,我在一个直接连接到Activity的视图中使用FragmentPagerAdapter和ViewPager.然后,FragmentPageAdapter从Activity移动到separat Fragment(现在是该活动的子代),作为重构的一部分.

这种变化并不顺利.例如,在方向更改后,缓存的选项卡会消失. NullPointerExceptions在我的Fragment子类中被抛出,因为findViewById无法找到它的View组件(看起来像片段的View层次结构在旋转更改后以某种方式被销毁).

我使用的是最新版本的Android支持库.

什么出错的想法?

编辑:

我目前的实施:

public class TabsPageAdapter extends FragmentPagerAdapter {

    ...

    @Override
    public Fragment getItem(int index) {
        // tabs = list of Fragment instances created in contructor of pager adapter - bad habbit?
        return tabs.get(index).getTabFragment();
    }

    ...

}


public class StatsFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.stats_view, container, false);

        TabsPageAdapter adapter = new TabsPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
        ViewPager viewPager = (ViewPager) root.findViewById(R.id.tabPager);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        TabPageIndicator pageIndicator = (TabPageIndicator) root.findViewById(R.id.tabIndicator);
        pageIndicator.setViewPager(viewPager);  
        return root;
    }
}


public class MedalsTab extends Fragment {

    private MedalAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.medals, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        this.adapter = new MedalAdapter();
        GridView gridView = (GridView) getActivity().findViewById(R.id.grdMedals);
        // Nullpointerexception is thrown here
        gridView.setAdapter(adapter);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //first saving my state, so the bundle wont be empty.
        //http://code.google.com/p/android/issues/detail?id=19917
        outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
        super.onSaveInstanceState(outState);
    }

    ...

}

我也在浏览寻呼机适配器中的标签时遇到此异常.

E/AndroidRuntime(28706): java.lang.NullPointerException
E/AndroidRuntime(28706):    at android.support.v4.app.Fragment.instantiate(Fragment.java:391)
最佳答案
以下是我解决问题的方法:

我更改了getItem方法来构造并返回一个新实例(感谢Luksprog):

    @Override
    public Fragment getItem(int index) {
        return tabs.get(index).constructFragment();
    }

我们需要使用getChildFragmentManger()返回的FragmentManager而不是getActivity().getFragmentManager()来创建片段,因为ViewPager驻留在片段中:

TabsPageAdapter adapter = new TabsPageAdapter(getChildFragmentManager(), getActivity());

转载注明原文:android – 在片段中使用FragmentPagerAdapter - 代码日志