android - 如何在 DataBinding Android 的 BindingAdapter 方法中提供默认值

标签 android android-layout kotlin android-databinding android-binding-adapter

我正在研究一种绑定(bind)适配器方法来设置 TextView 中的颜色范围.

@BindingAdapter("foregroundColorSpan", "start", "end", requireAll = false)
fun TextView.setForegroundColorSpan(color: Int, start: Int = 0, end: Int = text.length - 1) {
    val spanBuilder = SpannableStringBuilder(text)
    spanBuilder.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = spanBuilder
}

这是我如何使用它
<TextView
        android:id="@+id/loginLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/narrow"
        android:text="@string/already_have_account_login"
        android:textColor="@color/grey_aee4e4e4"
        android:textSize="@dimen/text_size_small"
        app:foregroundColorSpan="@{@color/blue_ae12235b}"
        app:start="@{25}" />

我似乎无法获得 end作为参数默认值,指定为 TextView 中文本的最后一个索引

是否有任何解决方法可以用来从参数中获取默认值,而无需检查该值是否为 0?

最佳答案

在 bindingAdapters 中不遵守默认值。生成的类在 Java 中,如果 requireAll 设置为 false,则未以编程方式设置的所有内容都将为 null、false(如果是 bool 值)或 0(对于数字)。
所以为了工作你的 BindingAdapter 函数应该是这样的:

@BindingAdapter(
    value = ["foregroundColorSpan", "start", "end"],
    requireAll = false
)
fun TextView.setForegroundColorSpan(color: Int, start: Int?, end: Int?) {
    val startValue = start ?: 0
    val endValue = end ?: text.length - 1
    val spanBuilder = SpannableStringBuilder(text)

    spanBuilder.setSpan(ForegroundColorSpan(color), startValue, endValue, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = spanBuilder
}

关于android - 如何在 DataBinding Android 的 BindingAdapter 方法中提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755614/

相关文章:

kotlin - kotlin 中的数据类继承?

exception - Android 应用程序无法在 HTC Desire 上运行,但在其他设备上运行良好

gradle - 使用 Gradle Kotlin 配置 Maven 插件

java - 点击提交按钮后程序崩溃

Android - 避免布局重复

android - 折叠工具栏标题消失

java - Gradle 构建因 "Error:Execution failed for task ' :app:mergeDebugResources'. > Crunching Cruncher photo.png 失败而失败”

Android Studio 不允许我使用 repeatOnLifecycle

android - 原生 ActionBar 到 ActionBarSherlock 的迁移

android - cocos2d-x 运行一个lua脚本两次