JohnAnders
JohnAnders

Reputation: 79

How pass callback from activity to fragment

In documentation is described method passing data from fragment to activity (https://developer.android.com/training/basics/fragments/communicating.html). I have opposite case I need pass data from activity to fragment. What is the best way setting callback to activity from fragment? I use (activity as MainActivity).setCallback(this) in a fragment and it works.

Upvotes: 1

Views: 1769

Answers (1)

benjiii
benjiii

Reputation: 553

In this case, your activity doesn't know if the fragment was created/wasn't destroyed. You can achieve what you want using liveData.

in MainActivity:

class MainActivity: BaseFragmentActivity() {
    val viewModel: CustomViewModel by viewModels()

    fun yourFunction() {
        viewModel.dataToPassToFragment.value = yourData
    }

}

the ViewModel:

class CustomViewModel: ViewModel() {
    var dataToPassToFragment = MutableLiveData<String>()
}

the fragment:

class CustomFragment: BaseFragment() {
    override val viewModel: CustomViewModel by activityViewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        viewModel.dataToPassToFragment.observe(this, Observer { data ->
            // do what you want with this data
        })
    }
}

Doing this, your activity doesn't need to know about the fragment and if the activity changes the data and the fragment is destroyed, you won't have any crash.

Upvotes: 1

Related Questions