I have a ViewPager that loads three pages at a time. If I swipe from page 1 to page 2 then to 3, the first page(fragment) goes to onPause()
. Then, if I swipe to the second page, 1st page comes to onResume()
even though the page 1 is still not visible to the user. So, my question is: how to distinguish between the first and second page in code? For example, if I have to run a piece of code when the fragment is visible, how is that done?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Override
setUserVisibleHint()
. This method will call once the fragment is visible to the user.user method pager.setOffscreenPageLimit(numbr) to set how many fragments you want in stack to be hold.
if your Fragment extend android.support.v4.app.Fragment
you can use this, it works for me.
Override setUserVisibleHint() this will call when fragment is visible to the user
Solve your problem:
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
1) Create LifecycleManager Interface The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
2) Let each Fragment implement the interface Add iplements statement for each class declaration:
3) Implement interface methods in each fragment In order to check that it really works as expected, I will just log the method call and show Toast:
4) Call interface methods on ViewPager page change You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:
5) Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
I didn't write the code. Full tutorial here: http://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/