View binding in traditional way using findViewbyId in LifecyclerObserver

124 Views Asked by At

I am new to the lifecycle observer (fragment). I am trying to link the views defined in XML with fragment. traditionally, we use to do it in onActivityCreated method using findViewById. How can we do it while using lifecycle observer?

Kindly do not suggest data binding. I am trying to avoid it in this scenario.

1

There are 1 best solutions below

1
On

You can do it this way

class TestFragment : Fragment(), LifecycleObserver {


@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun doSomethingOnActivityCreated(){
    requireActivity().lifecycle.removeObserver(this)
    
    //do stuff
}

override fun onAttach(context: Context) {
    super.onAttach(context)
    requireActivity().lifecycle.addObserver(this)
}

}