ViewPager in TabFragment not loading second time

与世无争的帅哥 提交于 2019-11-30 06:17:39

问题


I'm trying to make an app that has a ViewPager in a Fragment that is part of a TabHost.

Everything works out fine. I have my tabbar, I can switch tabs. When I switch to the tab with the ViewPager, all is shown correctly. But as soon as I leave this tab with the ViewPager and return this tab, my content is not shown. If I scroll to the side twice i do see my next image. And if I go back two times I also see the images are loaded (probably the offscreenloaded) See that my TabFragment is being reinstantiated when i return to it but the fragments in the ViewPager aren't.

I've included a screen mockup and some of my code.

Can anybody help?

Cheers!

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    mProjectText = (TextView) getView().findViewById(R.id.projectText);
    mProjectText.setText(mActiveProject.getInspirationText());

    mAdapter = new AlbumAdapter(getFragmentManager(), mActiveProject.getInspiration());

    mPager = (ViewPager)getView().findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);


    super.onActivityCreated(savedInstanceState);
}




public class AlbumAdapter extends FragmentStatePagerAdapter {

private ArrayList<ProjectContent> mItems;

public AlbumAdapter(FragmentManager fm, ArrayList<ProjectContent> items) {
    super(fm);
    this.mItems = items;
}

@Override
public Fragment getItem(int position) {
    return AlbumContentFragment.newInstance(mItems.get(position));
}

@Override
public int getCount() {
    return mItems.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}}


回答1:


I found the problem. It took me two days, but hey, it's fixed.

Instead of using

mAdapter = new AlbumAdapter(getFragmentManager(), mActiveProject.getInspiration());

You should use

mAdapter = new AlbumAdapter(getChildFragmentManager(), mActiveProject.getInspiration());

So much for 5 characters.




回答2:


I been searching this for long finally found a solution.Change your page adapter instance FragmentPagerAdapter to FragmentStatePagerAdapter example:

class PageAdapter extends FragmentStatePagerAdapter {



回答3:


you should use getChildFragmentManager() instead of getFragmentManager() and FragmentStatePagerAdapter() instead of FragmentPagerAdapter().Hope it will be useful for someone.



来源:https://stackoverflow.com/questions/16960676/viewpager-in-tabfragment-not-loading-second-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!