可以将 Kotlin 的 isNullOrBlank() 函数导入 xml 以用于数据绑定

Can Kotlin's isNullOrBlank() function be imported into xml for use with data binding

通过数据绑定,我正在设置文本字段的可见性。可见性取决于字符串为 null 或为空或两者皆无。

<?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">

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

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

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        <TextView
            android:id="@+id/textField1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{viewModel.data.text}"
            android:visibility="@{(viewModel.data.text == null || viewModel.data.text.empty) ? View.GONE : View.VISIBLE}"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/> 

    </android.support.constraint.ConstraintLayout>

是否可以在数据元素中创建导入,以便我可以使用 kotlin.text.StringsKt class 中的 isNullOrBlank() 函数?

本来希望可以这样用的:android:visibility="@{(viewModel.data.title.isNullOrBlank() ? View.GONE : View.VISIBLE}"

TextUtils.isEmpty() 随心所欲。

Android 数据绑定仍然从 XML 生成 Java 代码而不是 Kotlin 代码,一旦数据绑定将迁移到生成 Kotlin 代码而不是 Java 我相信我们将能够在 XML 中使用 Kotlin 扩展功能,这将非常酷。

我相信随着 Google 大力推动 Kotlin,这很快就会发生。但是现在,您有以下

TextUtils.isEmpty() 正如@Uli 所提到的不要忘记写一个导入。

为什么不能在xml中使用StringKt.isNullOrBlack的原因:

下面是来自 Kotlin 的代码 String.kt

@kotlin.internal.InlineOnly
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
    contract {
        returns(false) implies (this@isNullOrEmpty != null)
    }

    return this == null || this.length == 0
}

如您所见,它带有 @kotlin.internal.InlineOnly 注释,表示此方法的 Java 生成代码将是私有的。

InlineOnly means that the Java method corresponding to this Kotlin function is marked private so that Java code cannot access it (which is the only way to call an inline function without actual inlining it).

这意味着它不能从 Java 调用,并且由于数据绑定生成的代码在 JAVA 中,它也不能用于数据绑定。拇指规则是您可以从 JAVA 访问的内容,如果不只是使用我会说的旧 Java 方式,您可以在数据绑定中使用它。