I am following a book for learning android development and I came across with the usage of Fragment.isAdded() method.
The documentation says it returns true when a fragment is added to its hosting activity. But I am confused on the difference between onAttach() and isAdded() methods. I want to understand when and why we should use Fragment.isAdded() method. And what is the difference between onAttach() and isAdded() in terms of their usages?
Thanks in advance.
onAttach(Context) gets called when "a fragment is first attached to its activity. onCreate(Bundle) will be called after this"
In other words, you override / implement this function in your Fragment, so that the Android system calls that function and let you know when the Fragment has been added to its Activity.
class YourFragment : Fragment() {
override fun onAttach(context: Context) {
// now you know this Fragment is attached to its activity
}
}
isAdded() is not called by the Android system, but can be called by you (the developer) to check if the Fragment is added to its Activity. It returns true if the fragment is currently added to its activity.
In other words, you are directly asking the Fragment whether it is added to its Activity, by calling this function.
This can be usefull when you have access to Fragments via FragmentManager and you want to do something with it. You may need to check if this Fragment is currently added to its Activity.
// assuming you got a reference to a fragment
if (fragment.isAdded()) { ... } else { ... }
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