I'm really curious about how to determine (from an outer class) if a fragment's onCreateView()
has already been called. I have searched for similar questions but found none.
For instance, is fragment.isAdded()
a good indicator?
My first thought was simply fragment.getView() != null
, but I'm not 100% sure it would be reliable as it seems, and I'm also slightly reluctant to use it (for no particular reason, I just tend to avoid nullity checks). I would be happy to find a workaround. Suggestions I had:
isAdded()
Return true if the fragment is currently added to its activity.
This line is quite ambiguous in my opinion; added is not attached, but neither created. It might refer to FragmentTransaction.add()
(which is semantically wrong because you can have <fragment>
s stuck in your layout without having to call add
or replace
).
Still, FragmentTransaction.add()
documentation gives no info nor makes you think added -> created
. I'd say no.
isVisible()
Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.
Looks good, in the sense that isVisible() -> isCreated
, but the third option makes it isCreated != isVisible
. I just think of fragments inside a view pager: not all are visible, but the fragments near the currently visible fragment are added, created and alive, you can call methods on them. But for them, isVisible() == false
. This is kind of too strict.
isInLayout()
Return true if the layout is included as part of an activity view hierarchy via the < fragment> tag. This will always be true when fragments are created through the < fragment> tag, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.
I don't think this applies here.
getView() != null
Returns The fragment's root view, or null if it has no layout.
This still looks the one and only solution. I'd just like a confirmation about that.
Implement a callback
..to be called onCreateView()
or, better, onViewCreated()
. But:
- I don't need to call something as soon as the fragment is created (why would you need that?), I need something to check at a given time;
- One should define the opposite, say, onViewNotAvailableAnymore(), to make the check meaningful at all times;
- I don't see how this would be different, or better, than
getView != null
.