我使用html . fromhtml在TextView中查看html。

Spanned result = Html.fromHtml(mNews.getTitle());
...
...
mNewsTitle.setText(result);

但是Html.fromHtml现在在Android N+中已弃用

我怎样才能找到做这件事的新方法?


当前回答

我有很多这些警告,我总是使用FROM_HTML_MODE_LEGACY,所以我做了一个名为HtmlCompat的助手类,包含以下内容:

   @SuppressWarnings("deprecation")
   public static Spanned fromHtml(String source) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
        } else {
            return Html.fromHtml(source);
        }
    }

其他回答

这是我的解决方案。

 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()));

    }

我有很多这些警告,我总是使用FROM_HTML_MODE_LEGACY,所以我做了一个名为HtmlCompat的助手类,包含以下内容:

   @SuppressWarnings("deprecation")
   public static Spanned fromHtml(String source) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
        } else {
            return Html.fromHtml(source);
        }
    }

比较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

来自官方文件:

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

你可以使用

//noinspection deprecation
return Html.fromHtml(source);

仅对单个语句而不是整个方法抑制检查。