我有一些带有一些项目的FragmentList。如果我单击某个项目,将打开包含Viewpager的相应片段。到目前为止没问题,但如果我回到List并再次单击该项,则不再调用方法getItem(int position)。
这里有类似问题的链接:
Display fragment viewpager within a fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_fragment_runtime, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
indicator = (TitlePageIndicator) view.findViewById(R.id.indicator);
MyFragmentPagerAdapter mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
indicator.setViewPager(mViewPager);
return view;
}
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter implements TitleProvider {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public String getTitle(int position) {
return muxbusTitles[position];
}
@Override
public Fragment getItem(int location) {
return muxbusFragmentList.get(location);
}
@Override
public int getCount() {
return muxbusTitles.length;
}
}
return view;
}
修改 如果有人感兴趣,解决方案是从PagerAdapter扩展而不是FragmentStatePagerAdpater,因为Viewpager已经在片段中了。
答案 0 :(得分:0)
我确实遇到过类似的问题,经过一段时间的努力,我做了一个自己的理解(假设),ViewPager
保留了子片段的引用进入内存甚至托管的Fragment or Activity
都被销毁(没有使用Activity测试)。所以我写了这个方法freeFragmentsFromViewPager()
。您需要从onDestroy()
的{{1}}拨打电话。
Fragment
这是我的适配器代码
/**
* This method free the child fragments from ViewPager as ViewPager keeps the reference
* of child fragments into memory and next time when you again come to visit view pager it won't show the fragment layout
* because it has the reference to the fragment whilst the fragment's view was already destroyed.
*/
private void freeFragmentsFromViewPager()
{
for(int i = 0; i < TabsFragmentPagerAdapter.fragments.length; i++)
{
Fragment fragment = TabsFragmentPagerAdapter.fragments[i];
if(fragment != null)
{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
TabsFragmentPagerAdapter.fragments[i] = null;
}
}
}