我想知道是否可以使用 DataBinding 有条件地显示基于方法 bool 响应的布局。这就是我正在尝试做的事情
XML 布局:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="View"
type="android.view.View"/>
<variable
name="App"
type="com.app.JTApp"/>
</data>
<include layout="@layout/view_checkout_total_cardview"
android:visibility="@{App.isLandscape() ? View.GONE : View.VISIBLE}" />
</layout>
JTApp 类:
public class JTApp {
public boolean isLandscape() {
Timber.d("putty-- isLandscape: --------------------------");
return getResources().getBoolean(R.bool.is_landscape);
}
…
}
目前这不起作用。我错过了什么或者这是不可能的吗?我来自网络,使用 Angular 这样的框架可以实现这一点。
最佳答案
是的,可以在 XML 中使用条件语句。我对数据绑定(bind)库不太熟悉,但documentation中使用了类似的功能。 :
Zero or more import elements may be used inside the data element. These allow easy reference to classes inside your layout file, just like in Java.
<data> <import type="android.view.View"/> </data>
Now, View may be used within your binding expression:
<TextView android:text="@{user.lastName}" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>
我相信您的代码的唯一问题是您正在使用 View
作为variable
而不是 import
在你的<data>
元素。
关于android - 是否可以根据类方法响应有条件地显示 XML 包含内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39978450/