Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace current Fragment in ViewPager on Android

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.

like image 645
kimv Avatar asked Oct 26 '15 09:10

kimv


People also ask

How to replace fragment in fragment Android?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container.

How to set ViewPager in Android?

To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .


1 Answers

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;
}
like image 71
Bas van Stein Avatar answered Nov 05 '22 03:11

Bas van Stein