Why not a duplicate: Suggested post only works for a viewpager, or when onResume is called.
I have a listfragment and a detailfragment. The detail fragment is opened when a list item is clicked. I accomplish this by hiding the listfragment and I showing the detailfragment. When the user goes back, he returns to the listfragment.
How can I detect when the user gets back to my fragment, or when my fragment is visible?
Please note that I would like to keep using .hide() and show() and that I am looking for a listener or a onVisible to check when the fragment becomes visible, and not a method to check if it is visible.
fragment:fragment:1.1. 0 you can just use onPause() and onResume() to determine which fragment is currently visible for the user. onResume() is called when the fragment became visible and onPause when it stops to be visible. To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
onStart()The onStart() method is called once the fragment gets visible.
EDIT:
As pointed out in the comments, setUserVisbileHint()
does not get called automatically, but by the FragmentPageAdapter when used in a ViewPager.
For the scenario described in the question, onHiddenChanged(boolean hidden)
http://developer.android.com/reference/android/app/Fragment.html#onHiddenChanged(boolean) is suitable.
As stated in the documentation, the method gets called every time the Fragments hidden state changes, but not on the initial setup of the Fragment.
You could use setUserVisibleHint()
http://developer.android.com/reference/android/support/v4/app/Fragment.html#setUserVisibleHint(boolean)
if isVisibleToUser
is set to true
the fragment should be displayed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With