我有一个自定义 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/