首页 > 解决方案 > 使用 DataBinding 使文本的某些部分变为粗体

问题描述

我想将我的文本的某些部分设置为粗体,其值是使用 DataBinding 和 ViewModel 设置的。

例如

如果您被选中,您将为您的配对支付160 美元。

我正在使用字符串资源

<string name="product_price">If you are selected, you will have to pay $%d for your pair.</string>

<TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginEnd="@dimen/spacing_xlarge"
          android:layout_marginStart="@dimen/spacing_xlarge"
          android:layout_marginBottom="@dimen/spacing_small"
          android:text="@{@string/product_price(productPrice)}"
          android:textColor="@color/button_tertiary"
          android:visibility="@{productPrice > 0}"
          style="@style/Body.Small"
          />

目前通过设置使用带有绑定的 ViewModel 传递产品价格binding.setProductPrice(Object.getPrice())

我知道以下解决方案:但想尝试使用 DataBinding

但上述所有解决方案都是解决方法。

问题 ::

Want to try DataBinding feature which can be used to style certain part of string. Just like SpannableString

Manipulate String in the Layout file using DataBinding

标签: androidandroid-databindingandroid-mvvm

解决方案


根据@CommonsWare,

通过添加基本 Html 标签尝试<string name="product_price">If you are selected, you will have to pay <![CDATA[<b>$%d</b>]]> for your pair.</string>

布局文件:导入的 Html

 <?xml version="1.0" encoding="utf-8"?>
 <layout
   <data>
   <import type="android.text.Html"/>
   <data>
     <LinearLayout>
       <android.support.design.widget.CoordinatorLayout>
       <TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginEnd="@dimen/spacing_xlarge"
          android:layout_marginStart="@dimen/spacing_xlarge"
          android:layout_marginBottom="@dimen/spacing_small"
          android:text="@{Html.fromHtml(@string/product_price(productPrice))}"
          android:textColor="@color/button_tertiary"
          android:visibility="@{productPrice > 0}"
          style="@style/Body.Small"
          />
       </android.support.design.widget.CoordinatorLayout>
     </LinearLayout>
 </layout>

推荐阅读