【问题标题】:Can Kotlin's isNullOrBlank() function be imported into xml for use with data bindingKotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定
【发布时间】:2018-08-23 12:37:51
【问题描述】:

通过数据绑定,我正在设置文本字段的可见性。可见性取决于字符串是否为空或空或两者都没有。

<?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 类中的 isNullOrBlank() 函数?

希望能够这样使用:android:visibility="@{(viewModel.data.title.isNullOrBlank() ? View.GONE : View.VISIBLE}"

【问题讨论】:

  • 我怀疑isNullOrBlank() 是作为扩展函数实现的,我不确定数据绑定表达式解析器处理这些的能力如何。我怀疑是否有一种使用import 的方法会有所帮助,因为它适用于类(以及接口和类似的东西),而不是函数。

标签: android kotlin android-databinding


【解决方案1】:

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

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

@Uli 提到的TextUtils.isEmpty() 不要忘记编写导入。

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 表示这个 Kotlin 对应的 Java 方法 函数被标记为私有,因此 Java 代码无法访问它(其中 是在没有实际内联的情况下调用内联函数的唯一方法 它)。

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

【讨论】:

  • 别忘了导入TextUtils
【解决方案2】:

TextUtils.isEmpty() 应该做你想做的事。

【讨论】:

  • 哇太棒了。它同时检查可空性和空性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2010-10-13
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多