Is Fragment.setUserVisibleHint() called by the android System?
Looking at the sources, it looks like this system is mostly intended for fragments put in a pager.
You (or the implementation of the fragment pager for example) should set it as a hint ("Hint provided by the app" as a comment in the Fragment
source says) so that it can, for example, defer its loading (initialization) if not visible and prioritize the loading of visible fragments (typical need when used into a pager, again).
Note though, that the FragmentPagerAdapter makes use of this and properly calls setUserVisibleHint()
on its fragments, which is why I guess you see some people advising to e.g. override setUserVisibleHint()
to know when a fragment gets visible to the user or not (and this would thus only work when the fragment is inside a FragmentPagerAdapter
, not when just put in a usual activity layout for example).
So to answer the question clearly: you call it manually, and FragmentPagerAdapter
also calls it manually.
Related videos on Youtube
vivek
A Post-Grad in chemistry. Programming is my hobby. I like c++ and python, into scala ad Clojure these days, and completely hate Java.
Updated on July 07, 2020Comments
-
vivek almost 4 years
Is
Fragment.setUserVisibleHint()
method called by the System , or
do we call it manually ? -
vivek over 11 yearsHad read that.. It doesn't talk about the system. Thanks anyway.
-
gMale about 9 yearsThis is part of the support v4 library and I'm using it right now on a Nexus One, running API 10, without any problems. There doesn't seem to be any reason why this won't run all the way down to API 4.
-
AndroidGuy over 7 yearsSo, what is the alternative to this, when a fragment is added in a normal activity.?
-
AndroidGuy over 7 yearsHow to call it manually ? Should we check return values of isAdded(), isHidden() .. ? isVisible() always returns false.
-
desseim over 7 years@AndroidGuy Unless you implement a class which manages fragments (like a fragment pager for example), you don't need to call
Fragment#setUserVisibleHint
. So if you simply add a fragment to an activity, you don't need to bother about it. To get better help, I suggest you clarify what you want to do (your problem) and search for it on StackOverflow, or ask a new question if none matches your problem perfectly. -
AndroidGuy about 7 yearsI wanted something which would tell me that my fragment is visible to the user. Your answer makes things clear. I have upvoted :) This worked when I was using a FragmentPagerAdapter. But, When my fragment was in an activity, without view pager, I checked the return value of getUserVisibleHint() & solved my issue. Thanks, anyways.