【问题标题】:strings.xml: How to remove underlining from the space preceding an <u> tag?strings.xml:如何从 <u> 标记之前的空格中删除下划线?
【发布时间】:2018-04-05 19:31:35
【问题描述】:

我的strings.xml 中有以下行:

<string name="test_string">This is a <u>test</u></string>

在我的活动 xml 中,我在 TextView 中引用了这个字符串:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/test_string" />

奇怪的是,当我在我的设备(小米米 A1,Android 8.0)上运行该应用程序时,&lt;u&gt; 前面的空格也会加下划线。注意“a”和“test”之间带下划线的空格(来自实际设备的屏幕截图):

我也尝试在strings.xml 中使用以下内容:

<string name="test_string">This is a&#032;<u>test</u></string>

但结果是一样的。有什么想法吗?

【问题讨论】:

  • 你试过 SpannableString 吗?
  • 这很好用。我是 Android 开发新手,以前从未使用过 SpannableString,但感谢您的评论和一些谷歌搜索,我能够让它工作。还发布了详细的答案,以防有人遇到类似问题。

标签: android textview android-styles


【解决方案1】:

我能够在我的模拟器上重现这个。为了解决,我改变了字符串资源如下:

<string name="underline">this is a &lt;u>test&lt;/u></string>

然后,我不是简单地将字符串设置为我的 TextView,而是首先通过 Html.fromHtml() 运行它:

TextView text = findViewById(R.id.text);
String withMarkup = getString(R.string.underline);
text.setText(Html.fromHtml(withMarkup));

【讨论】:

  • 是的,这行得通。实际上,我更喜欢这个解决方案,而不是我在自己的答案中使用 SpannableString 提出的解决方案。通过您的回答,您不必为每个单独的字符串指定开始和结束字符位置。如果您有多个带有下划线的字符串要处理,这将使其更加有用。
  • 请注意,fromHtml 方法现在已被弃用。现在您必须将 fromHtml 方法与 fromHtml(String source, int flags) 或 fromHtml(String source, int flags, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) 一起使用。
【解决方案2】:

您的字符串必须用" 字符包围

<string name="test_string">"This is a <u>test</u>"</string>

它会避免&lt;u&gt; 标签前的下划线空格

【讨论】:

    【解决方案3】:

    我能够使用 SpannableString 解决这个问题。在活动的 Java 代码中添加了以下内容:

    TextView testView = findViewById(R.id.test_view);
    SpannableString testContent = new SpannableString(getResources().getString(R.string.test_string));
    // underlining only "test" in "this is a test"
    // note that 10 is the character BEFORE the first char we want to underline
    // and 14 is the last char we want to underline
    testContent.setSpan(new UnderlineSpan(), 10, 14, 0);
    testView.setText(testContent);
    

    显然,在本例中,活动 xml 中的 TextView id 应该是 test_view

    这样,“a”和“test”之间的空格就没有下划线了。

    【讨论】:

    • 此代码有效,但仅适用于该特定字符串。实际上,您可以根据该语言指定开始和结束索引。如果我们需要设置粗体样式的出现以法语、德语等的另一个索引开头怎么办?会发生转变
    【解决方案4】:

    我能够让它与空间的 XML 字符一起使用。

    <string name="test_string">This is a&#160;<u>test</u></string>
    

    【讨论】:

    • ]> 这是一个 测试
    • cmets 中缺少换行符确实很不幸,但我不想发布新答案只是为了指出您可以从 HTML 中教给 XML 字符实体名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2012-02-07
    相关资源
    最近更新 更多