M'hamed
M'hamed

Reputation: 2598

Communicate with other fragments - why best practice changed

Why Android team changed best practice to how to assign an interface to fragment.

Before it was on the fragment onAttach(context: Context) we cast the context to the interface.

private lateinit var onHeadlineSelectedListener: OnHeadlineSelectedListener

override fun onAttach(context: Context?) {
    super.onAttach(context)
    onHeadlineSelectedListener = activity as OnHeadlineSelectedListener
}

Now Android recommend to do it on onAttachFragment() here's the link below:

class MainActivity : Activity(), HeadlinesFragment.OnHeadlineSelectedListener {
    // ...

    fun onAttachFragment(fragment: Fragment) {
        if (fragment is HeadlinesFragment) {
            fragment.setOnHeadlineSelectedListener(this)
        }
    }
}

https://developer.android.com/training/basics/fragments/communicating#kotlin

Upvotes: 1

Views: 58

Answers (1)

Ahmad Najar
Ahmad Najar

Reputation: 66

It's better now to use viewModel to save the state of the data or the action and you can have live data in between

1.so create the activity and then create SheredViewModel

2.add livedata:LiveData

  1. add your view model to your activity by viewModelProviders.of(this)[SheredViewModel]

  2. add the observer in the activity if you want to listen to the changes in the activity or any where else

  3. go to you'r fragment add the viewModelProviders.of(activity)[SheredViewModel]

  4. now in this case if you post any data to the liveData:LiveData any one can listen to your changes elegant and clean

you can have a look on the android document for this example in this link

https://developer.android.com/topic/libraries/architecture/viewmodel

Upvotes: 1

Related Questions