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 the ViewPager has 3 fragments to display: Fragment1 , Fragment2 , Fragment3 . Fragment1 is a fragment of a grid and displays a grid. Fragment2 and Fragment3 have their own content to display. When the screen appears on the screen, ViewPager display the next fragment - Fragment2 . And so on.

What I need?

I want that when you click an element from the grid ( Fragment1 displayed), Fragment1 should be completely replaced with some other fragment, say Fragment4 (this is another fragment and does not return using the included adapter). The user will work with Fragment4 and after ButtonBack click (just the iside button Fragment4 ), Fragment1 with the grid should be displayed again. Meanwhile, the ViewPager should behave the same as when scrolling, the following fragment will be shown (in our case Fragment2 ).

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

My question

So can this be achieved? If so, how? I would really appreciate your help. Alex PS Sorry for my English :)

+7
android replace android-fragments android-viewpager fragmentpageradapter
source share
3 answers

One way to achieve this is to add another FragmentActivity that your Fragment4 will display. Use Intent to start this operation and send the position of the grid position or other data to Extra .

When you click on the hinged head, this action will be completed, and the last activity with a view pager will be displayed.

[EDIT] Old answer. More effective solutions are provided in other answers,

0
source share

I made a small example that shows how to achieve it:

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

I think you need to use another fragment as a container.

+15
source share

You will need to complete the fragment transaction and add the existing fragment to the backstack. I created a sample project to show you how to do this.

The code is not configured correctly, I just created it to show you how to do it.

https://drive.google.com/folderview?id=0BxHClVwHSqq5dVRvT1Qyd0hYN0k&usp=sharing

But remember that even if you click on any pager viewing screen, the previous fragment ends, showing that this is the same action.

IF this is not the expected behavior, then you should consider using several actions (e.g. tab layout)

0
source share

All Articles