Replace current Fragment in ViewPager on Android

两盒软妹~` 提交于 2019-12-23 10:06:27

问题


I have a ViewPager and I have to replace the first Fragment if a certain action happens.

public static class PagerAdapter extends FragmentStatePagerAdapter{

    private TempChannel latestChannel;
    private VideosFragment.SortType sortType;

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                if(latestChannel == null) {
                    return new LatestVideosFragment();
                }else{
                    return VideosFragment.getVideosFragment(latestChannel, sortType);
                }
            case 1:
                return new LiveVideosFragment();
            case 2:
                return new ConversationsFragment();
        }
        return null;
    }
}

Basically, when I click a channel in the LatestVideosFragment, the first position in the adapter should change to an instance of the VideosFragment class.

public void startLatestChannelFragment(TempChannel channel, VideosFragment.SortType sortType){
    adapter.setLatestChannel(channel, sortType);
    adapter.notifyDataSetChanged();
    Log.d("x", "on channel started");
}

I assumed that calling notifyDataSetChanged() on the adapter would update the fragment, but it does not. Also tried calling invalidate() on the ViewPager without any effect. The Fragment is updated only if I go to the third tab, and then return to the first.


回答1:


Check the answers here for some good solutions: ViewPager PagerAdapter not updating the View

Basically overwriting getItemPosition in your PagerAdapter will give you the desired effect.

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


来源:https://stackoverflow.com/questions/33342613/replace-current-fragment-in-viewpager-on-android

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