我在一些Android代碼中進行了一些重構,其中我將FragmentPagerAdapter與ViewPager一起使用,直接連接到Activity。然後,將FragmentPageAdapter從Activity移動到單獨片段(現在是該活動的子節點),作爲重構的一部分。在片段中使用FragmentPagerAdapter
這個改變並不順利。例如,緩存的標籤在方向更改後會消失。 NullPointerExceptions在我的Fragment子類中的所有地方被拋出,因爲findViewById無法找到它的View組件(看起來像Fragments的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)
我附上當前代碼 – bjorncs 2013-03-04 08:20:19