Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when fragment becomes visible [duplicate]

Tags:

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.

like image 212
Mdlc Avatar asked Feb 12 '14 16:02

Mdlc


People also ask

How to determine when Fragment becomes visible in ViewPager?

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.

What is ViewPager2?

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 .

Which method is called once the fragment gets visible?

onStart()The onStart() method is called once the fragment gets visible.


1 Answers

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 isVisibleToUseris set to truethe fragment should be displayed.

like image 79
super-qua Avatar answered Oct 05 '22 23:10

super-qua