2023年9月22日 星期五

【Android】 LiveData 與 ViewModel


簡介

LiveData 的部分特性 : 
  • 可儲存數據 : 是可與任何數據搭配使用的封裝容器
  • 可觀察 : 儲存的數據發生更改時,觀察器會收到通知
  • 具有生命週期感知能力 : 會與 LifecycleOwner (通常是 activity 或 fragment) 關聯, LiveData 僅更新處與活躍生命週期狀態 ( 如 STARTED 或 RESUMED) 的觀察器。

初始化

private val _currentScrambledWord = MutableLiveData<String>() //可變的
val currentScrambledWord: LiveData<String> //不可變
get() = _currentScrambledWord

private val _score = MutableLiveData(0)
val score: LiveData<Int>
   get() = _score

使用

_currentScrambledWord.value = "string test"

使用在 ViewModel 中的 LiveData

<方法一> 將觀察器(obverse)附加到 ViewModel 中的 LiveData 變數上

舉例 :
將 LiveData 的值顯示(給 view)。
// Observe the scrambledCharArray LiveData, passing in the LifecycleOwner and the observer.
viewModel.currentScrambledWord.observe(viewLifecycleOwner,
   { newWord ->
       binding.textViewUnscrambledWord.text = newWord
   })

<方法二> 使用 Databinding,綁定 viewLifecycleOwner,直接在 layout 使用 LiveData

// Specify the fragment view as the lifecycle owner of the binding.
// This is used so that the binding can observe LiveData updates
binding.lifecycleOwner = viewLifecycleOwner
在 fragment 的 onViewCreated() 方法內將生命週期擁有者傳遞給版面配置。

在你已將其轉成 data binding 的 layout file 中 (若沒轉則需要轉) :
<data>
    <variable
        name="gameViewModel"
        type="com.example.android.unscramble.ui.game.GameViewModel" />
</data>

android:text="@{gameViewModel.currentScrambledWord}"


如果需要傳遞字串資源:

(舉例 : 傳給 <string name="score">score : %d</string>)

android:text="@{@string/score(gameViewModel.score)}"

多參數也行
android:text="@{@string/word_count(gameViewModel.currentWordCount, maxNoOfWords)}"

參考資料


相關文章

0 comments:

張貼留言