class TestFragment : Fragment() {
private lateinit var checkBox2er: CheckBox
private lateinit var checkBox3er: CheckBox
// ...
private lateinit var checkBox10er: CheckBox
private val activityViewModel: MainViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_test, container, false)
checkBox2er = rootView.findViewById(R.id.checkbox2TT)
checkBox3er = rootView.findViewById(R.id.checkbox3TT)
// ...
checkBox10er = rootView.findViewById(R.id.checkbox10TT)
val checkBoxes = listOf(
checkBox2er, checkBox3er, checkBox4er, checkBox5er,
checkBox6er, checkBox7er, checkBox8er, checkBox9er, checkBox10er
)
// update CheckBox from ViewModel
// IS THIS ACTUALLY NEEDED?
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
activityViewModel.testFactors.collect { updatedFactors: Set<Int> ->
Log.d(javaClass.simpleName, "testFactors was updated")
checkBoxes.forEach { checkBox ->
checkBox.tagNumber?.let { rowId -> checkBox.isChecked = updatedFactors.contains(rowId) }
}
}
}
}
// update ViewModel Set when a CheckBox is clicked
checkBoxes.forEach { checkBox ->
checkBox.setOnCheckedChangeListener { clickedCheckBox, isChecked ->
clickedCheckBox.tagNumber?.let { rowId ->
Log.d(javaClass.simpleName, "clicked CheckBox $rowId")
activityViewModel.toggleCheckbox(rowId, isChecked)
}
}
}
return rootView
}
}
val View.tagNumber: Int?
get() {
val stringTag = this.tag as? String
return stringTag?.toIntOrNull()
}
a的布局看起来像这样:
CheckBox
我在我的<CheckBox
android:id="@+id/checkbox2TT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:checked="true"
android:text="@string/TT2"
android:tag="2" />
:中管理当前所有选定的
Set
CheckBox
我现在很困惑是否真的需要
ViewModel
。根据我的理解,ViewModel应该是MVVM中真相的单调源,但是当申请过程被杀死时,似乎商店似乎是
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val writableTestFactors: MutableStateFlow<Set<Int>> = MutableStateFlow(sortedSetOf(2,3,4,5,6,7,8,9,10))
val testFactors: StateFlow<Set<Int>> = writableTestFactors
fun toggleCheckbox(toggleRow: Int, isChecked: Boolean) {
val newSortedSet = TreeSet(testFactors.value)
if (isChecked) {
newSortedSet.add(toggleRow)
} else {
newSortedSet.remove(toggleRow)
}
writableTestFactors.value = newSortedSet
}
}
商店,并恢复了
lifecycleScope.launch {}
ES本身的检查状态。
这里应该是什么真理的来源,我将如何正确实施MVVM方法?
您对此正确,但是,对于活动或碎片甚至UI控件,现在在Ongreate之前调用了OnviewStaterEstored(SavedInstance并非无效)。您现在可以咨询活动源代码