android - 使用 DataBinding 使文本的某些部分变为粗体

标签 android android-databinding android-mvvm

我想将我的文本的某些部分设置为粗体,其值是使用 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"
          />

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

我知道以下解决方案:但想尝试使用 DataBinding
  • 使用 Html 文本 - 但不想在代码中使用它。
  • 在水平样式中使用不同的 TextView。将该产品价格的样式设置为粗体。 - 非常糟糕的做法
  • 使用 SpannableString - 但不想在代码中使用它。

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

    问题::
    Want to try DataBinding feature which can be used to style certain part of string. Just like SpannableStringManipulate String in the Layout file using DataBinding

    最佳答案

    根据@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>
    

    关于android - 使用 DataBinding 使文本的某些部分变为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822203/

    相关文章:

    android - 在 Android 中获取并显示相机 View 的部分区域

    android - 数据绑定(bind)和包含的布局 : Cannot find setter attribute for onClick

    具有自定义绑定(bind)逻辑的 Android 双向数据绑定(bind)

    android - Robotium 测试用例文档,Android

    android - 是否有用于指定设备类型、操作系统版本、应用程序版本等的移动 http 请求的标准 header ?

    android - 来自同一 Android 应用程序的用户之间的 GCM

    java - 如何将数据绑定(bind)与 DialogFragment 一起使用

    android - 何时使用 executePendingBindings() 何时不需要?

    如果快速调用,android LiveData Observable 不会返回数据

    android - MVVM-包含布局内的 Recyclerview 从未初始化