数据绑定从字符串中删除 html 标签

问题描述 投票:0回答:5

我想在数据绑定中使用 xml 资源字符串中的简单标签。

public class StringUtils {
    public static String text(String a) {
        return a;
    }
}

XML:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{StringUtils.text(@string/underlined_text)}" />

字符串:

    <string name="underlined_text">This is a <u>underlined</u> text.</string>

最后当我调试文本方法时我意识到< u >标签被删除了。

android data-binding
5个回答
2
投票

很可能它从一开始就不存在。

在字符串资源中,识别的内联 HTML 元素(如

<u>
)被解释为资源的一部分。如果您调用
getString()
,这些 HTML 元素将被删除。如果您在
getText()
上调用
Resources
,您将获得包含标记的
CharSequence
(例如,
UnderlineSpan
)。

由于您在任何地方都使用

String
,因此您的 HTML 元素将被忽略。

我不太确定为什么要以这种方式设置数据绑定。如果您使用:

android:text="@string/underlined_text"

你会得到你想要的,而且更快。毕竟,

StringUtils
什么也没做。

但是,如果您确实确定要使用数据绑定:

  • 使用您的字符串资源 ID 在
    getText()
    上调用
    Resources
  • 传递
    CharSequence
    以获取数据绑定表达式

或者,您可以将字符串资源的内容包装在

CDATA
中,以保持原始 HTML 完整。但在某些时候,您可能需要使用
Html.fromHtml()
或类似的东西来获取应用了格式的
CharSequence


1
投票

要在数据绑定中的字符串资源中使用 html 标签:

字符串:

<string name="underlined_text">This is a &lt;u>underlined&lt;/u> text.</string>

布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <import type="android.text.Html" />
    </data>

    <your_root_view>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{Html.fromHtml(@string/underlined_text)}" />
    </your_root_view>
</layout>

Android Studio 4.1.3

中测试了此方法

0
投票

您可以尝试使用 HTML 转义码:

<string name="underlined_text">This is a &lt;u&gt;underlined&lt;/u&gt; text.</string>

我还想问这里是否真的需要数据绑定 - 你可以只使用

android:text="@string/underlined_text"

编辑:还遇到了这个答案这可能对你有用


0
投票

怎么样:

android:text="@string/underlined_text"

您可以像这样更改定义的字符串以保留跨区字符串:

<string name="underlined_text">This is a &lt;u&gt;underlined&lt;/u&gt; text.</string>

0
投票

使用

@text/underlined_text
代替
@string/underlined_text

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{@text/underlined_text}" />

我没有在任何地方找到它的记录,但它有效。

© www.soinside.com 2019 - 2024. All rights reserved.