Android get view model in Activity and Fragment
First, make sure this dependency is included in the app gradle file.
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
Assume there is a view model called NfcViewModel.kt with the following code.
import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NfcViewModel : ViewModel() { private val _text = MutableLiveData().apply { value = "" } val text: LiveData = _text fun setText(message: String) { _text.value = message } }
Import viewModels, get reference of NfcViewModel, and set data on the NfcViewModel by calling a function from this view model.
import androidx.activity.viewModels private val nfcViewModel: NfcViewModel by viewModels() nfcViewModel.setText("Hello World!")
Import activityViewModels, get the reference for this ViewModel, and listen for data from the property text of this view model.
import androidx.fragment.app.activityViewModels private val nfcViewModel: NfcViewModel by activityViewModels() val textView: TextView = binding.editMessage nfcViewModel.text.observe(viewLifecycleOwner) { textView.text = it }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts