How to replace Fragment inside ViewPager, using Pa

2020-06-15 06:31发布

问题:

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:)

回答1:

One way to achieve this is by adding another FragmentActivity that displays your Fragment4. Use Intent to start this activity and sent grid item position or other data in Extra.

On press of backbutton this activity will be finished and last activity with view pager will be displayed.

[EDIT] Old response. Better solutions are provided in other answers,



回答2:

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.



回答3:

You will have to do the fragment transaction and add the existing fragment into backstack. I created a sample project to show you how to do it.

The code is not fine tuned, I just created it to show you how to do it.

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

But please be aware that even if you press back at any of the view pager screen, the previous fragment ends up showing as it is the same activity.

IF this is not expected behavior, then you should consider having multiple activities instead ( like tab layout )