是否可以使用数据绑定来绑定当前布局元素?例如,我想在点击复选框时显示一些文字,所以我希望有这样的东西:
<CheckBox
android:id="@+id/myCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="check me"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text"
android:visibility="@{myCheckBox.isChecked() ? View.VISIBLE : View.GONE}" />
我知道如何从java代码中执行此操作,我只是想知道是否有办法通过仅修改xml文件来实现此类行为?
答案 0 :(得分:2)
在ViewModel中创建一个可观察字段。
public class ViewModel {
public ObservableBoolean mCheckBox = new ObservableBoolean(false);
}
修改布局xml文件:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="@={viewModel.mCheckBox}"
android:text="check me" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text"
android:visibility="@{viewModel.mCheckBox ? View.VISIBLE : View.GONE}" />