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

问题描述

我希望在布局文件中有条件地设置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”。

This link might help you.

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...