我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
使用以下代码获取解决方案:
textView.setText(fromHtml("<Your Html Text>"))
实用性方法
public static Spanned fromHtml(String text)
{
Spanned result;
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(text);
}
return result;
}
其他回答
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标记。
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
如果您希望能够通过xml配置它,而不需要对java代码进行任何修改,您可能会发现这个想法很有用。只需从构造函数调用init并将文本设置为html
public class HTMLTextView extends TextView {
... constructors calling init...
private void init(){
setText(Html.fromHtml(getText().toString()));
}
}
xml格式:
<com.package.HTMLTextView
android:text="@string/about_item_1"/>
只需使用:
String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));