我使用对片段的弱引用来跟踪片段状态页面适配器中的片段。我发现它比制作一个向量来跟踪实际片段更便宜。那么我可以调用一个名为 getFragmentt(2) 的函数,它会在我的弱引用列表中搜索片段,如果它还活着,它将返回真实对象。到目前为止一切顺利。现在,如果我旋转设备,fragmentManager 会重新创建片段,但弱引用会因此而丢失。当在方向改变时重新创建片段时,适配器甚至不会被调用。这是代码。
public class SectionsPagerAdapter extends FragmentStatePagerAdapter{
ArrayList<WeakReference<Fragment>> m_fragments;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
m_fragments=new ArrayList<WeakReference<Fragment>>();
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a listFragment ) with the page number as one of its argument.
TweetsListFragment mListfragment = TweetsListFragment.newInstance(
position, nf, mpageTitles[position]);
m_fragments.add(position, new WeakReference<Fragment>(mListfragment));
return mListfragment;
}
@Override
public int getItemPosition(Object object) {
printLog(Consts.TAG, "getting item position from pageview adapter");
return PagerAdapter.POSITION_NONE;
}
@Override
public int getCount() {
return mpageTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mpageTitles[position];
}
/*return actual object from weak store of fragments on request*/
public Fragment getFragment(final int position) {
return m_fragments.get(position) == null ? null :
m_fragments.get(position).get();
}
......... etc