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

Android 在布局XML中将TextView textStyle有条件地设置为斜体,android,kotlin,android-databinding,Android,Kotlin,Android Databinding,我希望在布局文件中有条件地设置TextView的textStyle属性。直接设置“normal”或“italic”效果很好,但如何基于数据绑定中的布尔值应用这两种设置之一呢 <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <da

我希望在布局文件中有条件地设置TextView的textStyle属性。直接设置“normal”或“italic”效果很好,但如何基于数据绑定中的布尔值应用这两种设置之一呢

<?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>

...
android:text=“一些文本”
android:textStyle=“@{isComplete?@string/textStyle\u normal:@string/textStyle\u italic}”

当我尝试运行上述程序时,错误并不清楚,但我的XXXBindingImpl类似乎无法生成。我可以在kotlin中以编程方式更新文本样式,但我很好奇是否有办法在视图本身中实现这一点。

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

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

在“type”中,您必须使用包名提供类的名称,例如“com.example.YourClass”,如上例所示


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

BindingAdapter.kt

xyz.xml:



本例中的类型已设置为布尔值。问题在于设置textStyle。仍然不确定为什么我尝试的基于字符串的三元结构不起作用,但不管怎样,它起作用了。
@JvmStatic
    @BindingAdapter("setTextCustomStyle")
    fun TextView.setTextCustomStyle(isNormal:Boolean){
        if (isNormal) this.setTypeface(this.typeface,Typeface.NORMAL) else this.setTypeface(this.typeface,Typeface.ITALIC)
    }
        <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"/>