在布局中有条件地将 TextView textStyle 设置为斜体 XML

Conditionally set TextView textStyle to italic in layout XML

我希望在布局文件中有条件地设置 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 class 似乎没有生成。我可以在 kotlin 中以编程方式更新文本样式,但我很好奇是否有办法让它在视图本身中工作。

您似乎已经设置了变量的“类型”

 <data>
    <variable
        name="isComplete"
        type="com.example.YourClass" />
 </data>

在“类型”中,您必须提供 class 的名称和包名称,例如“com.example.YourClass”,如上例。

This link might help you.

您可以使用绑定适配器来实现:

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"/>