ViewModelFactory in Android
Overview
ViewModelFactory is used to create objects of ViewModel. When you want to use initialize a parameter your ViewModel at the time of its object creation then you must use ViewModelFactory.
Steps to Follow
- Add the required dependency in build.gradle (Module) file
// ViewModel
def viewModel_version = "2.4.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$viewModel_version"
- Create a class and extend it with ViewModel() class. Write the logic in this class.
class MainViewModel(private val initialValue: Int) : ViewModel() {
/* Do not make the variable private because you have to use this variable in MainActivity */
var counter: Int = initialValue;
/* Do not make the function private because you have to use this function in MainActivity */
fun increment() {
counter++
}
}
- Create a class and implement it with ViewModelProvider.Factory interface
class MainViewModelFactory(private val counter: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MainViewModel(counter) as T
}
}
- Create an instance of ViewModel in MainActvity (or the Activity where you want to display the data) and use its instance to run the method defined in ViewModel class and / or use its instance to display the properties defined in ViewModel
class MainActivity : AppCompatActivity() {
private var counter: Int = 0;
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel =
ViewModelProvider(this, MainViewModelFactory(10))[MainViewModel::class.java]
setContent()
}
/* Do not declare the fun as private because this function is declared in the xml file of the activity*/
fun increment(view: View?) {
mainViewModel.increment()
setContent()
}
private fun setContent() {
tvCounter.text = mainViewModel.counter.toString()
}
}
Comments
Post a Comment