我有一个有趣的问题。在我的代码中,我动态创建了一些RadioButtons并将其添加到RadioGroup。但是我无法理解如何使用mvvm和数据绑定而不使用xml以编程方式向每个RadioButtons添加可观察的布尔值...因此,例如,如果我们在xml静态中有RadioButtons,我们将拥有类似的东西:
<RadioButton
android:id="@+id/someRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="@{viewModel.isChecked}"
android:text="@string/some_string" />
和
ObservableBoolean isChecked = new ObservableBoolean(false);
在我们的代码中。但是,如果我们在xml中没有按钮却在代码中添加了按钮,那么如何添加可观察字段呢?喜欢
RadioButton radioButton = new RadioButton(this)
radioButton.text = localeLanguage.languageName
RadioGroup.LayoutParams params = RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT)
radioButton.layoutParams = params
return radioButton
请参见official doc。通过xxxBinding = DataBindingUtil.inflate(layoutInflater, R.layout.xxx, viewGroup, false);
,然后是xxxBinding.checked = isCheked
,您将获得xxxBinding。
您可以使用如下所示的LiveData:
ViewModel {
val _radioCheckedLiveData = MutableLiveData<Boolean>()
val radioCheckedLiveData: LiveData<Boolean> = _radioCheckedLiveData
private fun setRadioChecked(checked: Boolean) = _radioCheckedLiveData.value = checked
// handle radio check event
fun radioChecked(checked: Boolean) {
if (checked) {
// do something and change the data source
}
fun xxxFun() {
// if you want to change radioButton check status by code, no need to set RadioButton's status directly
setRadioChecked(true)
}
}
}
Activity {
val radioButton = RadioButton(context)
viewModel.radioCheckedLiveData.observe(this) {checked->
radioButton.checked = checked == true
}
radioButton.setOnCheckedListener {checked->
viewModel.radioChecked(checked)
}
}