Replace current fragment in ViewPager on Android

I have a ViewPager , and I have to replace the first Fragment if a specific 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 on a channel in LatestVideosFragment , the first position in the adapter should be replaced with 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 will update the fragment, but that is not the case. Also tried calling invalidate( ) on the ViewPager without any effect. Fragment updated only if I go to the third tab and then go back to the first.

+5
source share
1 answer

Check answers for some good solutions: ViewPager PagerAdapter does not update the view

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

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

Source: https://habr.com/ru/post/1234518/


All Articles