【问题标题】:Databinding remove html tags from string数据绑定从字符串中删除 html 标签
【发布时间】:2019-06-19 17:45:42
【问题描述】:

我想在数据中使用来自 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>

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

【问题讨论】:

    标签: android data-binding


    【解决方案1】:

    很可能一开始就不存在。

    在字符串资源中,已识别的内联 HTML 元素(如 &lt;u&gt;)被解释为资源的一部分。如果您调用getString(),这些 HTML 元素将被删除。如果你在 Resources 上调用 getText(),你会得到一个包含标记的 CharSequence(例如,UnderlineSpan)。

    由于您在任何地方都使用String,因此您的 HTML 元素将被忽略。

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

    android:text="@string/underlined_text"
    

    你会得到你想要的,而且更快。毕竟StringUtils 什么都不做。

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

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

    或者,您可以将字符串资源的内容包装在 CDATA 中,以保持原始 HTML 的完整性。但是,在某些时候,您需要使用 Html.fromHtml() 或类似的东西来获取应用格式的 CharSequence

    【讨论】:

      【解决方案2】:

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

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

      我还想问这里是否真的需要数据绑定 - 你可以使用 android:text="@string/underlined_text"

      编辑:还遇到了this answer,可能对你有用

      【讨论】:

        【解决方案3】:

        怎么样:

        android:text="@string/underlined_text"
        

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

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

        【讨论】:

          【解决方案4】:

          在数据绑定的字符串资源中使用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

          中测试了这个方法

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-02-05
            • 2019-01-06
            相关资源
            最近更新 更多