Mdlc Mdlc - 12 days ago 7
Android Question

Detect when fragment becomes visible

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.

Answer

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.