我在一些 Android 代码中做了一些重构,我在直接连接到 Activity 的视图中使用 FragmentPagerAdapter 和 ViewPager。作为重构的一部分,FragmentPageAdapter 然后从 Activity 移动到一个单独的 Fragment(现在是该 Activity 的子项)。
这种变化并不顺利。例如,在方向更改后,缓存的选项卡会消失。NullPointerExceptions 在我的 Fragment 子类中随处可见,因为 findViewById 无法找到它的视图组件(看起来片段的视图层次结构在旋转更改后以某种方式被破坏)。
我正在使用最新版本的 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)