Igor
Igor

Reputation: 1201

strings.xml: How to remove underlining from the space preceding an <u> tag?

I have the following line in my strings.xml:

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

In my activity xml I reference this string in a TextView:

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

Weirdly enough, when I run the app on my device (Xiaomi Mi A1, Android 8.0), the space preceding the <u> also gets underlined. Note the underlined space between "a" and "test" (screenshot from actual device):

device

I have also tried using the following in strings.xml:

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

But the result is the same. Any ideas?

Upvotes: 3

Views: 1531

Answers (4)

StevenTB
StevenTB

Reputation: 410

Your string must be surrounded with the " character

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

It will avoid the underlined space preceding your <u> tag

Upvotes: 2

Surekha
Surekha

Reputation: 610

I was able to get it to work with the XML character for space.

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

Upvotes: 1

Igor
Igor

Reputation: 1201

I was able to solve this using SpannableString. Added the following to activity's Java code:

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);

Obviously, in this example your TextView id in activity xml should be test_view.

This way, the space between "a" and "test" is not underlined.

Upvotes: 1

Ben P.
Ben P.

Reputation: 54204

I was able to reproduce this on my emulator. To solve, I changed the string resource as follows:

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

Then, rather than simply setting the string to my TextView, I ran it through Html.fromHtml() first:

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

Upvotes: 5

Related Questions