ViewModel本身具有生命週期,可以在螢幕翻轉時讓數據保存不丟失,並配合MVVM的架構來達到數據與View(Activity、 Fragment)的分離,通常會與LiveData一起使用。
class MyViewModel : ViewModel() {
val info = MutableLiveData<String>()
}
class MyViewModel(application: Application) : AndroidViewModel(application) {
val info = MutableLiveData<String>()
}
val myViewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(application)
)
.get(MyViewModel::class.java)
//Layout裡的TextView
info.setOnClickListener {
myViewModel.info.value = "Hello JetPack!"
}
//ViewModel裡的LiveData
myViewModel.info.observe(this, Observer {
info.text = it
})
android {
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "androidx.fragment:fragment-ktx:1.3.2"
}
//AppCompatActivity
val myViewModel by viewModels<MyViewModel>()
//Fragment
val myViewModel by activityViewModels<MyViewModel>()
//Layout裡的TextView
info.setOnClickListener {
myViewModel.info.value = "Hello JetPack!"
}
//ViewModel裡的LiveData
myViewModel.info.observe(this, Observer {
info.text = it
})