问题描述
我希望在布局文件中有条件地设置TextView的textStyle属性。设置“正常”或“斜体”直接效果很好,但是如何基于数据绑定中的布尔值来应用这两个之一?
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="isComplete"
type="boolean" />
</data>
...
<TextView>
android:text="Some Text"
android:textStyle="@{isComplete ? @string/textStyle_normal : @string/textStyle_italic}"
</TextView>
当我尝试运行以上命令时,错误尚不清楚,但我的XXXBindingImpl类似乎无法生成。我可以在kotlin中以编程方式更新文本样式,但是我很好奇是否有一种方法可以在视图本身中使它起作用。
解决方法
您可以使用“绑定适配器”来实现:
BindingAdapter.kt
@JvmStatic
@BindingAdapter("setTextCustomStyle")
fun TextView.setTextCustomStyle(isNormal:Boolean){
if (isNormal) this.setTypeface(this.typeface,Typeface.NORMAL) else this.setTypeface(this.typeface,Typeface.ITALIC)
}
xyz.xml:
<TextView
android:id="@+id/tvItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{item.title}"
setTextCustomStyle="@{isComplete}"
tools:text="some text"/>
,
好像您已经设置了变量的“类型”
<data>
<variable
name="isComplete"
type="com.example.YourClass" />
</data>
在“类型”中,您必须为类的名称提供包名称,例如上例所示的“ com.example.YourClass”。