android - 如何使用 Android 数据绑定(bind)库制作粗体文本

标签 android android-databinding

非常基本,我想根据文本是否被阅读来将消息标题加粗。我似乎找不到解决方案。

这是我的 XML 代码:

            <TextView
                android:text="@{message.title}"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="5dp"
                android:layout_toLeftOf="@+id/timestamp"
                android:textSize="18sp"
                android:textStyle='@{message.isRead() ? "bold" : "normal"}'
                android:textColor='@{message.isRead() ? 0xff313131 : 0xff0662ab}' />

颜色变化效果很好,只有粗体文本给我带来了一些问题。

错误:任务 ':app:compileDebugJavaWithJavac' 执行失败。

java.lang.RuntimeException: Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'android:textStyle' with parameter type java.lang.String on android.widget.TextView. file:D:......xml loc:39:41 - 39:79 ****\ data binding error ****

最佳答案

一个简单的方法

public class TextViewBindingAdapter {
    @BindingAdapter("isBold")
    public static void setBold(TextView view, boolean isBold) {
        if (isBold) {
            view.setTypeface(null, Typeface.BOLD);
        } else {
            view.setTypeface(null, Typeface.NORMAL);
        }
    }
}

XML:

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:isBold="@{item.bold}"/>

关于android - 如何使用 Android 数据绑定(bind)库制作粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609328/

相关文章:

Android - 如何使用数据绑定(bind)从 XML 传递 View 对象

android - 如何在 7"两个不同的平板电脑上设置布局?

android - 我有一个应用程序/网络应用程序,但我找不到构建它所需的答案

android - 如何解决com.android.ide.common.internal.LoggedErrorException

java - 使用包含标签的 Android 数据绑定(bind)

android - 表达式中 ObservableFields 的 get()

android - Unresolved reference : FragmentTitleBinding

java - 如何在android中操纵 Volley 响应?

Android - 一定时间后重定向到另一个屏幕

Android NavigationDrawer中的双向数据绑定(bind)