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

时间:2018-10-19 08:56:40

标签: android android-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>

应该发生的是,“高级框”的可见性与切换按钮的“已检查”状态一起切换。我已经确认切换按钮中的双向数据绑定在viewModel中正确设置了布尔值“ advancedShown”。但是,在AdvancedBox类(扩展了LinearLayout)中从未调用过“ setVisibility”方法。

我尝试的其他方法是在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">

这两种方法均无法解决。我的问题是为什么它不起作用?在这种情况下使用数据绑定的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您的exports.getAllTours = function(req, res) { getTours() .then(data => console.log(data)) .catch(err => console.log(err )); } async function getTours() { var sql = "Select * from product_prd" return new Promise(async function (resolve, reject) { let rows; let fields; try { [rows, fields] = await promisePool.query(sql, args); } catch (err) { reject(err); } setTimeout(function () { resolve(rows); }, 500); }); } 应该是ObservableField或标有viewModel.advancedShown的注释(在第二个变体中,您需要在@Bindable上手动调用notifyPropertyChanged(BR.advancedShown)来触发更改) 。您可以在official docs

中找到更多信息。