Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Fragment inside ViewPager, using PagerAdapter?

My problem

I am using a ViewPager to display fragments inside a FragmentActivity. ViewPager gets fragments from the attached FragmentPagerAdapter.

mViewPager = (ViewPager) findViewById(R.id.view_pager);       
mAdapter = new HomePagerAdapter(getSupportFragmentManager());    
mViewPager.setAdapter(mAdapter);

Suppose ViewPager has 3 fragments to display: Fragment1, Fragment2, Fragment3. Fragment1 is a grid fragment and displays a grid. Fragment2 and Fragment3 have their own content to display. When the use swipes on the screen, ViewPager will display the next fragment - Fragment2. And so on.

What I want?

What I want is that, when an item from the grid (displayed by Fragment1) is clicked, Fragment1 should be completely replaced with some other fragment, say Fragment4 (this is different fragment and is not returned by the attached adapter). User will work on Fragment4 and after ButtonBack click (just button iside Fragment4), Fragment1 with the grid should be displayed again. Meanwhile ViewPager should behave the same i.e on swipe, the next fragment (in our case Fragment2) will be displayed.

So I just want to get the same behavior as in example: http://developer.android.com/training/basics/fragments/fragment-ui.html#Replace

My question

So, is this possible to achieve? If yes, then how to? I would greatly appreciate for your help. Alex. P.S. Sorry for my English:)

like image 223
AlexMomotov Avatar asked Sep 11 '13 15:09

AlexMomotov


People also ask

How do I refresh a ViewPager fragment?

OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter. Then, instead of creating a new Fragment, use the one contained in the adapter: mViewPager. addOnPageChangeListener(new ViewPager.

How do you call ViewPager fragment from activity?

You'll just need to cast it to the real fragment class if you want to call a specific method. int pos = viewpager. getCurrentItem(); Fragment activeFragment = adapter. getItem(pos); if(pos == 0) ((NPListFragment)activeFragment).

Is PagerAdapter deprecated?

This method is deprecated.

How do I pass data from activity to fragment in ViewPager?

The updateFragmetData method will be called in the current selected viewpager item fragment. You can also add a tag parameter to updateFragmetData so that you can be sure the right fragment instance is called. If required you can call isVisible in updateFragmetData implementation to make sure the fragment is visible.


1 Answers

I've made a little example that shows how to achieve it:

https://github.com/danilao/fragments-viewpager-example

I think the point is to use another fragment as a container.

like image 50
dlao Avatar answered Oct 22 '22 00:10

dlao