首先在布局文件中,使用RadioGroup和RadioButton来创建相应的组件,并为RadioButton设置一个id作为每个选项的标识符。例如:
接下来,在数据绑定类中定义相应的属性。例如:
public class MyViewModel extends BaseObservable { private int selectedOptionId;
@Bindable
public int getSelectedOptionId() {
return selectedOptionId;
}
public void setSelectedOptionId(int selectedOptionId) {
this.selectedOptionId = selectedOptionId;
notifyPropertyChanged(BR.selectedOptionId);
}
public void onSubmitClicked() {
// 获取所选RadioButton的id
int id = radioGroup.getCheckedRadioButtonId();
if (id != -1) {
// 设置选中的选项id
setSelectedOptionId(id);
}
}
}
最后,在提交按钮的onClick()方法中,调用ViewModel中定义的onSubmitClicked()方法。例如:
可以通过绑定属性的方式,将选中的选项与相应的RadioButton进行绑定。例如: