Android数据绑定:有没有一种显示/隐藏包含标记的好方法?
我刚刚开始在安卓系统中处理数据绑定。理想情况下,我希望有一个包含一些通用xml元素的根xml文件,然后它的内部内容可以是三个类似这样的xml文件之一Android数据绑定:有没有一种显示/隐藏包含标记的好方法?,android,android-layout,android-databinding,Android,Android Layout,Android Databinding,我刚刚开始在安卓系统中处理数据绑定。理想情况下,我希望有一个包含一些通用xml元素的根xml文件,然后它的内部内容可以是三个类似这样的xml文件之一 <data> <variable name="action" type="com.example.android.action"/> </data> <TextView> <TextView> <!--Only show one of these includes based
<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的视图:可见性
,还是我忽略了其中的一些内容
我应该使用android的视图:可见性吗
是的,最好的方法是在数据绑定布局中检查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>
在这里,您可以如上所述检查
NULL
或Boolean
。记住为包含的布局提供一个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(obj!=null&!(obj.getText().toString.isEmpty)):即如何实现:if(TextUtils.isEmpty(action.textData))visibility=GONE;能见度=可见;