看起来 DataBinding 以某种特殊方式处理 android:textAppearance(至少在 Android Studio 3.2.1 上)。
例如根据this的下面的表达式应该没问题,但不是。
编译器正在接受以下表达式,但它什么也不做:
android:textAppearance="@{R.style.MyStyleTest}"
我已经尝试了几种选择,只有香草方法对我有用:
android:textAppearance="@style/MyStyleTest"
作为解决方案
我建议使用@BindingAdapter 并在那里执行所有逻辑。
例如,如果您想使用对属性的引用(类似于:?attr/...),请使用以下方法:
layout.xml
<TextView
...
bind:textAppearanceAttr="@{position==1 ? android.R.attr.textAppearanceLarge: android.R.attr.textAppearanceMedium}"
/>
sources.kt
@BindingAdapter(value = ["textAppearanceAttr"])
fun textAppearanceAttr(textView: TextView, @AttrRes attrRef: Int?) {
attrRef?.also {
val attrs = textView.context.obtainStyledAttributes(intArrayOf(attrRef))
val styleRes = attrs.getResourceId(0, -1)
attrs.recycle()
if (styleRes != -1) {
TextViewCompat.setTextAppearance(textView, styleRes)
}
}
}
或者如果是样式资源 ID (@style/...):
layout.xml
bind:textAppearanceStyle="@{position==1 ? R.style.MyStyleTest1: R.style.MyStyleTest2}"
sources.kt
@BindingAdapter(value = ["textAppearanceStyle"])
fun textAppearanceStyle(textView: TextView, @StyleRes style: Int?) {
style?.also { TextViewCompat.setTextAppearance(textView, it) }
}