通过数据绑定在 XML 中切换自定义视图的可见性

Toggle visibility of custom view in XML via Databinding

我有一个片段布局 fragment_config.xml,其中包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:bind="http://schemas.android.com/tools">
    <data>
        <import type="android.view.View"/>
        <variable name="viewModel" type ="...GlobalConfigViewModel"/>
    </data>
        ...
            <ToggleButton
                android:id="@+id/btnShowAdvanced"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textOff="Show Advanced"
                android:textOn="Hide Advanced"
                android:checked="@={viewModel.advancedShown}"/>


            <com.minh.minh.pumpnotifier.global.configuration.AdvancedBox
                android:id="@+id/advancedBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="@{viewModel.advancedShown ? View.VISIBLE : View.GONE}"
                app:viewModel = "@{viewModel}"/>

    ...
</layout>

应该发生的是高级框的可见性随切换按钮的 "checked" 状态切换。我已经确认切换按钮中的双向数据绑定正确设置了 viewModel 中的布尔值 "advancedShown"。然而,"setVisibility"-方法从未在 AdvancedBox-class(它扩展了 LinearLayout)中被调用。

我尝试的其他方法是在 advanced_box.xml 的根元素中设置可见性绑定,因为它也有对 viewModel 的引用:

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <import type="android.view.View"/>
        <variable
            name="viewModel"
            type="...GlobalConfigViewModel" />
    </data>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/advancedSettings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="@{viewModel.advancedShown ? View.VISIBLE : View.GONE}"
        android:orientation="vertical">

虽然这两种方法都行不通。我的问题是为什么它不起作用,在这种情况下使用数据绑定的正确方法是什么?

你的viewModel.advancedShown应该是ObservableField or marked with @Bindable annotation (in the second variant you need manually invoke notifyPropertyChanged(BR.advancedShown) on your GlobalConfigViewModel to trigger changes). You can find more information in official docs