我在我的项目中使用的是dataBinding,当我有了xml,它是很好的工作:
<TextView
android:id="@+id/txtDateCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.format(@string/DateCreate,others.created)}" />但是当我换到咆哮的时候,让我崩溃:
<TextView
android:id="@+id/txtDateCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{Html.fromHtml(String.format(@string/DateCreate,others.created))}" />在我的string.xml中:
<resources>
<string name="DateCreate">open : <![CDATA[<b><font color=#FF0000>%s</b>]]></string>
</resources>发布于 2017-05-10 08:26:22
认为您需要首先在xml中导入html。
<data>
<import type="android.text.Html"/>
</data>
<TextView
android:id="@+id/txtDateCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{Html.fromHtml(String.format(@string/DateCreate,others.created))}" />发布于 2020-02-07 19:19:06
我认为视图不应该有任何逻辑/转换来显示数据。我建议做的是为此创建一个BindingAdapter:
@BindingAdapter({"android:htmlText"})
public static void setHtmlTextValue(TextView textView, String htmlText) {
if (htmlText == null)
return;
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(htmlText);
}
textView.setText(result);
}然后在布局中像往常一样调用它:
<TextView
android:id="@+id/bid_footer"
style="@style/MyApp.TextView.Footer"
android:htmlText="@{viewModel.bidFooter} />其中,viewModel.bidFooter具有获取文本字符串/跨/Chars的逻辑,同时考虑到不直接依赖于上下文、活动等
发布于 2020-09-18 13:46:12
下面的行在Android (API级别24)中被废弃。
Html.fromHtml(content)现在,您应该提供两个参数(内容和标志),如下所示:
Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)所以我建议您使用@BindingAdapter,如下所示:
object BindingUtils {
@JvmStatic
@BindingAdapter("loadHtml")
fun loadHtml(textView: TextView, content: String?){
if (!content.isNullOrEmpty()) {
textView.text = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(content)
}
}
}}
在XML文件中:
<data>
<import type="com.example.utils.BindingUtils"/>
</data>
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:loadHtml="@{String.format(@string/DateCreate,others.created))}"/>https://stackoverflow.com/questions/43886956
复制相似问题