【发布时间】:2019-07-08 23:26:25
【问题描述】:
我有一个布局文件,它定义了一个包含九个RadioButtons 的RadioGroup。此布局文件多次包含在片段布局中。
对于RadioGroup 布局的每个包含,我想以某种方式将所选RadioButton 的索引绑定到片段ViewModel 中的不同MutableLiveData<Integer> 变量,每个代表用户在多个九点量表上选择的分数。
数据绑定设置正确并适用于其他部分(例如,绑定点击处理程序和查看MutableLiveData<Boolean> 的可见性)。
到目前为止,我尝试做的是将我的 ViewModel 变量和/或不同的 MutableLiveData<Integer> 变量传递给包含的布局
...
<data>
<variable name="viewModel" type="my.package.MyViewModel"/>
<variable name="someVariable" type="androidx.lifecycle.LiveData<Integer>"/>
</data>
...
<include layout="@layout/radiobuttons"
app:viewModel="@{viewModel}"
app:someVariable="@{someVariable}"/>
并在RadioGroup 布局中使用相同的变量声明,以便能够在其中使用它们。然后我尝试使用绑定到RadioGroup 的android:onItemSelected 属性
android:onItemSelected="@{(parent, view, position, id) -> someVariable.setValue(position)}"
导致数据绑定错误:“在 android.widget.RadioGroup 上找不到参数类型为 lambda 的属性 'android:onItemSelected' 的设置器”
或将以下内容添加到RadioButtons
android:onClick="@{(view) -> viewModel.updateRadioButtonSelection(someVariable, /*INDEX HERE e.g.*/ 0)}"
但这给出了数据绑定错误“在 my.package.MyViewModel 类中找不到方法 updateRadioButtonSelection(java.lang.Integer, int)”,这意味着 MutableLiveData<Integer> 不是这样传递的,而是包含类型(我在 ViewModel 类中有一个方法public void updateRadioButtonSelection(MutableLiveData<Integer> variable, int value))。
我可以在布局中指定一个绑定,其中RadioButton 被选择到一个int 变量,而无需绕道涉及额外的代码并将RadioButton ids 转换为索引?单向绑定就足够了 - 不打算从代码中更改 ViewModel 变量。
【问题讨论】:
标签: android android-layout android-databinding