我使用html . fromhtml在TextView中查看html。
Spanned result = Html.fromHtml(mNews.getTitle());
...
...
mNewsTitle.setText(result);
但是Html.fromHtml现在在Android N+中已弃用
我怎样才能找到做这件事的新方法?
我使用html . fromhtml在TextView中查看html。
Spanned result = Html.fromHtml(mNews.getTitle());
...
...
mNewsTitle.setText(result);
但是Html.fromHtml现在在Android N+中已弃用
我怎样才能找到做这件事的新方法?
当前回答
这是我的解决方案。
if (Build.VERSION.SDK_INT >= 24) {
holder.notificationTitle.setText(Html.fromHtml(notificationSucces.getMessage(), Html.FROM_HTML_MODE_LEGACY));
} else {
holder.notificationTitle.setText(Html.fromHtml(notificationSucces.getMessage()));
}
其他回答
来自官方文件:
fromHtml(String)方法在API级别24中已弃用。使用fromHtml(String, int) 代替。 to_html_段落_lines_continuous选项toHtml(span, int):将以“\n”分隔的连续文本行换行<p> 元素。 to_html_段落_lines_individual选项toHtml(span, int):将每一行由'\n'分隔的文本包装在<p>或<li>内 元素。
https://developer.android.com/reference/android/text/Html.html
比较fromHtml()的标志。
<p style="color: blue;">This is a paragraph with a style</p>
<h4>Heading H4</h4>
<ul>
<li style="color: yellow;">
<font color=\'#FF8000\'>li orange element</font>
</li>
<li>li #2 element</li>
</ul>
<blockquote>This is a blockquote</blockquote>
Text after blockquote
Text before div
<div>This is a div</div>
Text after div
对于Kotlin用户,我们可以使用String.parseAsHtml()扩展函数,它使用HtmlCompat,反过来有兼容性检查。
这可以从androidx.core:core-ktx的android核心kotlin扩展中获得
尝试以下支持基本html标签,包括ul ol li标签。 创建一个标签处理程序,如下所示
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.TagHandler;
import android.util.Log;
public class MyTagHandler implements TagHandler {
boolean first= true;
String parent=null;
int index=1;
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equals("ul")) parent="ul";
else if(tag.equals("ol")) parent="ol";
if(tag.equals("li")){
if(parent.equals("ul")){
if(first){
output.append("\n\t•");
first= false;
}else{
first = true;
}
}
else{
if(first){
output.append("\n\t"+index+". ");
first= false;
index++;
}else{
first = true;
}
}
}
}
}
将文本设置为Activity,如下所示
@SuppressWarnings("deprecation")
public void init(){
try {
TextView help = (TextView) findViewById(R.id.help);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
help.setText(Html.fromHtml(getString(R.string.help_html),Html.FROM_HTML_MODE_LEGACY, null, new MyTagHandler()));
} else {
help.setText(Html.fromHtml(getString(R.string.help_html), null, new MyTagHandler()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
和html文本资源字符串文件作为
<![CDATA[…原始HTML数据…]] >
或者你可以使用androidx.core.text.HtmlCompat:
HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)
HtmlCompat纪录片