我需要为类中的布尔属性设置两个绑定,以便在将值提供给绑定时,XML将检查Yes
或No
RadioButton
,并在用户更改值时返回必须将其更新回类(UserSignupViewModel)中的变量。]>
变量为boolean resFlag;
Android通过android:checkedButton
支持RadioButton的两种方式绑定,但是很难理解,因为需要在XML中将哪些内容传递给此属性?
绑定适配器已由Android和it is here定义
根据two way binding的文档,android:checkedButton
已经支持内置的双向绑定,我在使用此属性设置双向绑定时遇到了麻烦,这是代码,
数据类,
public class UserSignupViewModel extends BaseObservable { static String TAG=UserSignupViewModel.class.getSimpleName(); private String userName; String firstName; String lastName; String emailId; boolean resFlag; @Bindable public boolean isResFlag() { return resFlag; } public void setResFlag(boolean resFlag) { this.resFlag = resFlag; } @Bindable public String getUserName() { return userName; } public void setUserName(String uname) { this.userName = uname; } @Bindable public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Bindable public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Bindable public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public void onSplitTypeChanged(RadioGroup radioGroup, int id) { Log.d(TAG,"onSplitTypeChanged() called"); radioGroup.check(radioGroup.getCheckedRadioButtonId()); } }
我的XML,
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> <variable name="userSignupViewModel" type="com.example.mysampleapp.UserSignupViewModel" /> </data> <LinearLayout xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="10dp" tools:context=".MainActivity"> <RadioGroup android:id="@+id/rGroupResident" style="@style/radioGroupStyle" android:onCheckedChanged="@{userSignupViewModel.onSplitTypeChanged}" > <RadioButton android:id="@+id/rbtnYes" style="@style/radioButtonStyle" android:layout_marginStart="0dp" android:checked="@{userSignupViewModel.resFlag}" android:text="Yes" /> <RadioButton android:id="@+id/rbtnNo" style="@style/radioButtonStyle" android:checked="@{userSignupViewModel.resFlag}" android:text="No" /> </RadioGroup> </LinearLayout> </layout>
如何使用
android:checkedButton
属性配置双向绑定?
这是我经历过的其他答案,
How to use Two way data binding with radio button in android
radio_checked.postValue(R.id.your_id1)//def value
不明白这段代码在做什么
后来发现了这个,How to bind method on RadioGroup on checkChanged event with data-binding
接受的答案未实现2种方式的绑定其他答案没有使用我上面提到的属性实现2向绑定,而是进行了字符串比较,我认为这不适合我要查找的内容。
我需要为一个类中的布尔属性设置两个绑定,以便在将值提供给绑定时,XML将检查Yes或No RadioButton,并在用户更改值时返回...
如果我理解您的问题,则需要设置一个OnCheckedChangeListener
,这将在您的单选组中注册更改,您可以根据自己的意愿在代码中进行反映。这是一个实现示例: