介绍
ViewModel可以自动感应生命周期储存和管理数据。
ViewModel从Repository获取数据,把数据提供给View。
LiveData在setValue(非UI线程使用postValue),会根据界面生命周期,回调更新UI界面。
build.gradle
1 2
| implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
|
ViewModel
1 2 3
| class WordViewModel : ViewModel(){ val allWords = MutableLiveData<List<Word>>() }
|
在Fragment中使用ViewModel
1 2 3 4
| ViewModelProviders.of(this).get(WordViewModel::class.java)
ViewModelProviders.of(activity!!).get(WordViewModel::class.java)
|
//接收
1 2 3 4 5 6 7
| wordViewModel.allWords.observe(this,object :Observer<List<Word>>{ override fun onChanged(t: List<Word>?) { } })
wordViewModel.allWords.observe(this, Observer { words -> })
|
当Fragment共享ViewModel时,Fragment1跳转Fragment2,Fragment1会被onDestroyView掉,回来会重走onCreateView。因此Fragment2的改动,Fragment1无法通过observe捕获。而是通过onCreateView重新根据ViewModel初始化UI。
简单的ViewModel类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class WordViewModel : ViewModel() { val allWords: MutableLiveData<List<Word>> init { val list = ArrayList<Word>() list.add(Word("DEFAULT")) list.add(Word("DEFAULT")) list.add(Word("DEFAULT")) list.add(Word("DEFAULT")) allWords = MutableLiveData() allWords.value = list } fun modify(position: Int, wordStr: String) { if (position > allWords.value?.size ?: 0 || position < 0 ){ return } allWords.value?.let { it[position].word = wordStr } } }
|