Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

java - How to display HTML string resource with parameters in TextView?

I have a HTML string like this:

Some text %1$s
<br></br>
<a href="https://stackoverflow.com/">StackOvewflow</a>
<br></br>
Contact: <a href="mailto:[email protected]">[email protected]</a>

How to display it so it shows the line breaks and links to the text properly in a TextView?

I have tried both

Spanned text = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    text = Html.fromHtml(getString(R.string.text, "parameter"), Html.FROM_HTML_MODE_LEGACY);
}
else
{
    text = Html.fromHtml(getString(R.string.text, "parameter"));
}
textView.setText(text);

and

String text = TextUtils.htmlEncode(getString(R.string.text, "parameter"));
textView.setText(text);

In the XML textView is defined as

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:text="@string/text"
        />

When displayed, it just looks like

Some text parameter StackOvewflow Contact: [email protected]

without any line breaks or links

question from:https://stackoverflow.com/questions/65866007/how-to-display-html-string-resource-with-parameters-in-textview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I used the same code you shared

  Spanned text = null;
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    text = Html.fromHtml(getString(R.string.text, "parameter"), 
    Html.FROM_HTML_MODE_LEGACY);
  }
  else
  {
    text = Html.fromHtml(getString(R.string.text), "parameter");
  }
  textView.setText(text);

seems to be working fine for me.

seems to be working


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...