在PreferenceFragmentCompat中使用Android ViewModel的解决方法如下:
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MyViewModel : ViewModel() {
private val _myData = MutableLiveData()
val myData: LiveData get() = _myData
fun updateData(newData: String) {
_myData.value = newData
}
}
class MyPreferenceFragment : PreferenceFragmentCompat() {
private lateinit var viewModel: MyViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
}
// ...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// ...
viewModel.myData.observe(viewLifecycleOwner) { newData ->
// 更新首选项的显示
val preference = findPreference("my_preference_key")
preference?.summary = newData
}
}
val button = view.findViewById
以上就是在 PreferenceFragmentCompat 中使用 Android ViewModel 的解决方法,通过 ViewModel 来管理数据,并使用 LiveData 来监听数据的变化,以更新首选项的显示。