How to replace Fragment inside ViewPager, using PagerAdapter?

北城余情 提交于 2019-12-21 04:16:20

问题


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 )



来源:https://stackoverflow.com/questions/18745600/how-to-replace-fragment-inside-viewpager-using-pageradapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!