Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why to use Fragment#isAdded() method in android? [duplicate]

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.

like image 320
Uzair Afridi Avatar asked Oct 29 '25 06:10

Uzair Afridi


1 Answers

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 { ... }
like image 75
ChristianB Avatar answered Oct 31 '25 21:10

ChristianB