android - 数据绑定(bind) : Pass resource id to custom view string attribute?

标签 android android-databinding

我有一个自定义 View ,其可样式属性定义为:

<declare-styleable name="CustomView">
    <attr name="stringAttribute" format="string"/>
</declare-styleable>

我想在初始化时将字符串资源传递给该 View ,这样我就可以通过 obtainStyledAttributes 获取它并立即将其应用到 View 。

但是,由于字符串资源是动态的,我似乎无法找到一种在不使用绑定(bind)适配器的情况下将其传递到 View 的方法。

Is it possible to pass a string resource ID to a custom view, without relying on a binding adapter?

所需的解决方案如下所示(其中资源 ID 是动态的):

app:stringAttribute="@{context.getString(R.string.value)}"

最佳答案

也许我没有正确理解你的问题,但你可以使用 BindingAdapter 配置绑定(bind)。例如,您可以按如下方式设置字符串资源:

TestBindings.kt

@BindingAdapter("stringRes")
fun setStringRes(view: TextView, @StringRes resource: Int) {
    view.text = view.context.getString(resource)
}

TestViewModel.kt

data class TestViewModel(@StringRes val text: Int)

test.xml

<?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>
        <variable
            name="viewModel"
            type="... .TestViewModel" />
    </data>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        stringRes="@{viewModel.text}"/>

</layout>

关于android - 数据绑定(bind) : Pass resource id to custom view string attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092414/

相关文章:

android - 在 APK 中动态启用/禁用调试功能的方法

android - Fragment 和父 Activity 一起生命周期

android - 在 Android 中将 GIF 添加到 ImageView

android - 双向数据绑定(bind)如何导致无限循环?

Android - Gradle 同步失败 : org/jetbrains/kotlin/kapt/idea/KaptGradleModelorg/jetbrains/kotlin/kapt/idea/KaptGradleModel

java - 在 Java 中将文件读入 byte[] 数组的优雅方法

Gradle 插件更新并迁移到 annotationProcessor 后,Android 数据绑定(bind)构建失败

android - Unresolved reference : FragmentTitleBinding

android - 如何在Android数据绑定(bind)中使用对象的方法?

android - 如何使用 Android 绑定(bind)库和 Kotlin 从 View 中绑定(bind) onClick 事件?