2017-07-30 14 views
0

是否可以使用数据绑定绑定当前布局元素?例如,我想显示一些文字被点击复选框的时候,所以我想有这样的事情:在Android MVVM中绑定当前布局元素

<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

有些家伙写的愚蠢的答案,我在评论礼貌地回答说,他是不正确,所以他删除了他的答案,然后downvoted我的问题;) – LLL

回答

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}" /> 
+0

谢谢,这是有道理的,虽然你写它需要ViewModel和Java代码,而我更感兴趣的解决方案,这将是XML只。毕竟我的复选框有它的ID,所以潜在的TextView可以引用它。但这些只是我的猜测,也许这是不可能的。 – LLL