在Android N中不推荐使用Html.fromHtml [英] Html.fromHtml deprecated in Android N

查看:1469
本文介绍了在Android N中不推荐使用Html.fromHtml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Html.fromHtmlTextView中查看html.

I am using Html.fromHtml to view html in a TextView.

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

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

But Html.fromHtml is now deprecated in Android N+

我如何/如何找到做到这一点的新方法?

What/How do I find the new way of doing this?

推荐答案

更新: 作为下面提到的@Andy Google创建了HtmlCompat可以代替以下方法使用.添加此依赖项implementation 'androidx.core:core:1.0.1 到应用程序的build.gradle文件.确保使用最新版本的androidx.core:core.

update: as @Andy mentioned below Google has created HtmlCompat which can be used instead of the method below. Add this dependency implementation 'androidx.core:core:1.0.1 to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core.

这使您可以使用:

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

您可以在 HtmlCompat文档

原始答案: 在Android N中,他们引入了新的Html.fromHtml方法. Html.fromHtml现在需要一个名为flags的附加参数.该标志使您可以更好地控制HTML的显示方式.

original answer: In Android N they introduced a new Html.fromHtml method. Html.fromHtml now requires an additional parameter, named flags. This flag gives you more control about how your HTML gets displayed.

在Android N及更高版本上,您应该使用此新方法.不推荐使用较旧的方法,并且在将来的Android版本中可能会删除该方法.

On Android N and above you should use this new method. The older method is deprecated and may be removed in the future Android versions.

您可以创建自己的Util方法,该方法将在较旧版本上使用旧方法,并在Android N及更高版本上使用较新方法.如果您不添加版本,请检查您的应用在较低的Android版本上是否会中断.您可以在Util类中使用此方法.

You can create your own Util-method which will use the old method on older versions and the newer method on Android N and above. If you don't add a version check your app will break on lower Android versions. You can use this method in your Util class.

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    if(html == null){
        // return an empty spannable if the html is null
        return new SpannableString("");
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // FROM_HTML_MODE_LEGACY is the behaviour that was used for versions below android N
        // we are using this flag to give a consistent behaviour
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        return Html.fromHtml(html);
    }
}

如果需要,可以将HTML.FROM_HTML_MODE_LEGACY转换为其他参数.这使您可以更好地控制使用哪个标志.

You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.

您可以阅读有关标签上不同标志的更多信息 HTML类文档

You can read more about the different flags on the Html class documentation

这篇关于在Android N中不推荐使用Html.fromHtml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆