android - 使用 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
- 使用 Html 文本 - 但不想在代码中使用它。
- 在水平样式中使用不同的 TextView。将该产品价格的样式设置为粗体。- 非常糟糕的做法
- 使用 SpannableString - 但不想在代码中使用它。
但上述所有解决方案都是解决方法。
问题 ::
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
解决方案
根据@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>
推荐阅读
- php - 未在 mailtrap 中收到正确 .env 的电子邮件
- sql - 具有差异模式的联合 2 表
- sql - 别名在使用时显示为无效的列名
- spring-boot - Sprint Boot Junit5 测试无法运行
- apache-flink - 保存点上的 Flink 应用程序失败
- azure - Azure 容器实例无法使用 docker compose 部署提取公共 docker hub 映像
- sql - 如何使这些 Active Record 查询更快?
- android - 如何在 android 中显示类似 YouTube 的涟漪效应?
- python - 删除同一列中的部分重复项,同时保留较长的文本?
- python - 如何使用 Python 中的嵌套循环创建基于 2 列的列?