Android 数据绑定:有显示/隐藏包含标签的好方法吗?

Android Data Binding: Is there a good way to show / hide an includes tag?

我刚刚开始弄乱 android 中的数据绑定。理想情况下,我希望有一个包含一些通用 xml 元素的根 xml 文件,然后它的内部内容可以是三个 xml 文件之一,如下所示

<data>
  <variable name="action" type="com.example.android.action"/>
</data>

<TextView>
<TextView>
<!--Only show one of these includes based on the binding data-->

<!-- if action.item -->
<include layout="item.xml"
 bind:item="@{action.item}">

<!-- else if action.udpate -->
<include layout="update.xml"
 bind:update="@{action.update}">

<!-- else if action.video -->
<include layout="video.xml"
 bind:video="@{action.video}">

<TextView>
... etc

所以基本上基于操作(项目、更新或视频)中存在的子对象显示它的布局并绑定视图但不显示其他包含。我应该只使用 android 的 View:Visibility 还是有一些我忽略的内容?

Should I just use android's View:Visibility

是的,最好的方法是检查 boolean 数据绑定布局并相应地设置可见性,如下所示。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    >

    <data>

        <import type="android.view.View"/>

        <variable
            name="action"
            type="com.example.android.action"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            layout="@layout/item"
            android:visibility="@{action.item ? View.VISIBLE: View.GONE}"/>

        <include
            layout="@layout/update"
            android:visibility="@{action.someOtherObject!=null ? View.VISIBLE: View.GONE}"/>

    </LinearLayout>
</layout>

在这里你可以检查NULLBoolean如上。

记得给包含的布局一个 id 否则它不会工作

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <import type="android.view.View"/>
        <variable
            name="show"
            type="Boolean" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:background="@color/colorPrimary">


        <include layout="@layout/progress"
            android:id="@+id/progress"
            android:visibility="@{show?View.VISIBLE:View.GONE}"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

实现这个

if(TextUtils.isEmpty(action.textData)) VISIBILITY = GONE; else VISIBILITY = VISIBLE;

您可以在数据标签中导入 TextUtils,然后在 xml 文件中使用 TextUtils isEmpty() 函数