我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
其他回答
如果在项目中使用androidx.*类,则应使用HtmlCompat.fromHtml(文本,标志)。
方法来源:
@NonNull
public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
if (Build.VERSION.SDK_INT >= 24) {
return Html.fromHtml(source, flags);
}
//noinspection deprecation
return Html.fromHtml(source);
}
使用HtmlCompat.fromHtml比使用Html.fromHtml更好,因为代码更少-只有一行代码,建议使用它。
看看这个:https://stackoverflow.com/a/8558249/450148
它也很好!!
<resource>
<string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
它只适用于少数标签。
public class HtmlTextView extends AppCompatTextView {
public HtmlTextView(Context context) {
super(context);
init();
}
private void init(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
} else {
setText(Html.fromHtml(getText().toString()));
}
}
}
更新以上答案
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
SiteLink= (TextView) findViewById(R.id.textViewSite);
SiteLink.setText(Html.fromHtml(value));
SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
如果您只想显示一些html文本,而实际上不需要TextView,那么使用WebView,如下所示:
String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);
这也不会限制您使用几个html标记。