Android 数据绑定默认变量值

Android Databinding default variable value

我有这个布局。

<data>
    <import type="android.view.View" />
    <variable
        name="shouldBeVisible"
        type="java.lang.Boolean" />
</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@={shouldBeVisible}" />

    <LinearLayout
        android:layout_width="40dp"
        android:layout_height="30dp"
        android:background="#dd0"
        android:visibility="@{shouldBeVisible ? View.VISIBLE : View.GONE}" />

</LinearLayout>

shouldBeVisible 默认为 false。 有没有办法使 shouldBeVisible 为真? 我想在这种情况下显示 LinearLayout。

到目前为止我正在使用 binding.shouldBeVisible=true

要解决该错误,您可以使用多种方法:

  1. 您可以使用具有反转逻辑的原始布尔类型(shouldBeVisible -> shouldBeHidden)

  2. 第二种方法是使用装箱的布尔类型(就像你现在使用的那样)并在表达式中设置默认值

  3. 第三种方式 - 在绑定膨胀后手动设置它(就像你现在已经做的那样)

    binding.shouldBeVisible=真

  4. 在数据绑定值中使用默认关键字

选择最符合您需求的一项。