我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
值得一提的是,从API级别24开始,Html.fromHtml(字符串源代码)方法已被弃用。如果这是你的目标API,你应该使用Html.fromHtml(字符串源,int标志)。
其他回答
简单使用Html.fromHtml(“Html字符串”)。这会奏效的。如果字符串具有类似<h1>的标记,则空格将出现。但我们无法消除这些空间。如果仍要删除空格,则可以删除字符串中的标记,然后将字符串传递给Html.fromHtml(“Html string”);方法。通常,这些字符串也来自服务器(动态),但如果将字符串原样传递给方法比从字符串中删除标记更好,则不经常这样做。
看看这个:https://stackoverflow.com/a/8558249/450148
它也很好!!
<resource>
<string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
它只适用于少数标签。
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());
我可以提出一个有点粗糙但仍然天才的解决方案吗!我从这篇文章中得到了这个想法,并将其改编为Android。基本上,您使用WebView,并在可编辑的div标记中插入要显示和编辑的HTML。这样,当用户点击WebView时,键盘就会出现并允许编辑。他们只需要添加一些JavaScript就可以取回编辑过的HTML,瞧!
代码如下:
public class HtmlTextEditor extends WebView {
class JsObject {
// This field always keeps the latest edited text
public String text;
@JavascriptInterface
public void textDidChange(String newText) {
text = newText.replace("\n", "");
}
}
private JsObject mJsObject;
public HtmlTextEditor(Context context, AttributeSet attrs) {
super(context, attrs);
getSettings().setJavaScriptEnabled(true);
mJsObject = new JsObject();
addJavascriptInterface(mJsObject, "injectedObject");
setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadUrl(
"javascript:(function() { " +
" var editor = document.getElementById(\"editor\");" +
" editor.addEventListener(\"input\", function() {" +
" injectedObject.textDidChange(editor.innerHTML);" +
" }, false)" +
"})()");
}
});
}
public void setText(String text) {
if (text == null) { text = ""; }
String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
// Init the text field in case it's read without editing the text before
mJsObject.text = text;
}
public String getText() {
return mJsObject.text;
}
}
这是Gist的组件。
注意:我不需要原始解决方案中的高度更改回调,所以这里没有,但如果需要,可以轻松添加。
每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。
因此,我们需要执行以下附加步骤,使其有效
public class CustomTextView extends TextView {
public CustomTextView(..) {
// other instructions
setText(Html.fromHtml(getText().toString()));
}
}