我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
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()));
}
}
}
更新以上答案
其他回答
如果在项目中使用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更好,因为代码更少-只有一行代码,建议使用它。
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标记。
我知道这个问题很老了。这里的其他答案建议使用Html.fromHtml()方法。我建议您使用androidx.core.text.HtmlCompat包中的HtmlCompat.fromHtml()。因为这是Html类的向后兼容版本。
示例代码:
import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;
String htmlString = "<h1>Hello World!</h1>";
Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);
TextView tvOutput = (TextView) findViewById(R.id.text_view_id);
tvOutput.setText(spanned);
通过这种方式,您可以避免Android API版本检查,并且它很容易使用(单行解决方案)。
如果您试图从字符串资源id显示HTML,则格式可能不会显示在屏幕上。如果发生这种情况,请尝试使用CDATA标记:
strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>
...
MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));
有关更多详细信息,请参阅本文。