我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
如果您希望能够通过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"/>
其他回答
使用以下代码获取解决方案:
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;
}
创建一个全局方法,如:
public static Spanned stripHtml(String html) {
if (!TextUtils.isEmpty(html)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
} else {
return Html.fromHtml(html);
}
}
return null;
}
您也可以在“活动/片段”中使用它,如:
text_view.setText(stripHtml(htmlText));
使用BindingAdapter:
@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
if (description != null) {
view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
view.movementMethod = LinkMovementMethod.getInstance()
} else {
view.text = ""
}
}
用法:
<TextView
android:id="@+id/content_text_view"
app:renderHtml="@{show.description}"
...
只需使用:
String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));
每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。
因此,我们需要执行以下附加步骤,使其有效
public class CustomTextView extends TextView {
public CustomTextView(..) {
// other instructions
setText(Html.fromHtml(getText().toString()));
}
}