Home > Enterprise >  How to reassign listener in onAttach of a fragment when parent is also a fragment instead of Activit
How to reassign listener in onAttach of a fragment when parent is also a fragment instead of Activit

Time:02-17

I know that in order to reassign listener when a fragment is recreated and fragment's parent is an activity, we assign listener instance in following way:


override fun onAttach(context: Context) {
    if(context is MyListener){
       this.listener = context
    }
}

As far as I know this context always refers to an activity.

How would I achieve the same in case parent of frament is also a fragment

CodePudding user response:

If you want to check to see if your parent fragment implements an interface, you should get access to the parent fragment via parentFragment (or requireParentFragment() if you want an always non-null parent fragment).

fun onAttach() {
    val parent = parentFragment
    if (parent is MyListener) {
       this.listener = parent
    }
}
  • Related