- Html.fromHtml устарел в Android N
- Формат html.fromHtml устарел в Android N
- 11 ответов
- флаг параметры:
- Html.fromHtml deprecated in Android N
- Flag parameters:
- Html.fromHtml deprecated in Android N
- Answers
- Android html fromhtml deprecated
- Example 1 Of Parse HTML File content Using WebView With Example In Android Studio:
- Example 2 Of HTML In Android Studio Using TextView:
- Example 3 Of HTML content in WebView With Example in Android Studio:
Html.fromHtml устарел в Android N
Я использую Html.fromHtml для просмотра HTML в TextView .
Но Html.fromHtml сейчас устарела в Android N +
Что / Как мне найти новый способ сделать это?
обновление : как @Andy упоминалось ниже, Google создал, HtmlCompat который можно использовать вместо метода ниже. Добавьте эту зависимость implementation ‘androidx.core:core:1.0.1 в файл build.gradle вашего приложения. Убедитесь, что вы используете последнюю версию androidx.core:core .
Это позволяет вам использовать:
Вы можете прочитать больше о различных флагах в HtmlCompat-документации.
оригинальный ответ: в Android N они представили новый Html.fromHtml метод. Html.fromHtml теперь требуется дополнительный параметр с именем flags. Этот флаг дает вам больше контроля над тем, как отображается ваш HTML.
На Android N и выше вы должны использовать этот новый метод. Более старый метод устарел и может быть удален в будущих версиях Android.
Вы можете создать свой собственный метод Util, который будет использовать старый метод в более старых версиях и новый метод в Android N и выше. Если вы не добавите версию, проверьте, что ваше приложение будет работать на более низких версиях Android. Вы можете использовать этот метод в своем классе Util.
Вы можете преобразовать HTML.FROM_HTML_MODE_LEGACY в дополнительный параметр, если хотите. Это дает вам больше контроля над тем, какой флаг использовать.
Вы можете прочитать больше о различных флагах в документации класса Html.
Источник
Формат html.fromHtml устарел в Android N
Я использую Html.fromHtml для просмотра html в TextView .
но Html.fromHtml теперь устарел в Android N+
что/как мне найти новый способ сделать это?
11 ответов
вы должны добавить проверку версии и использовать старый метод на Android M и ниже, на Android N и выше вы должны использовать новый метод. Если вы не добавите версию, проверьте, что ваше приложение сломается на более низких версиях Android. Этот метод можно использовать в классе Util.
флаг параметры:
вы можете прочитать больше о различных флагах на HTML-код класса документация
У меня было много этих предупреждений, и я всегда использую FROM_HTML_MODE_LEGACY, поэтому я сделал вспомогательный класс HtmlCompat, содержащий следующее:
сравнить флаги fromHtml ().
Если вам посчастливилось развиваться на Котлине, просто создайте функцию расширения:
и тогда так сладко использовать его везде:
этот метод был
устаревшийна уровень API 24.
вы должны использовать FROM_HTML_MODE_LEGACY
отдельные элементы блочного уровня с пустыми строками (две новые строки персонажи) между ними. Это устаревшее поведение до Н.
код
Для Котлин
из официального документа :
fromHtml(String) метод устарел на уровне API 24. использовать fromHtml(String, int) вместо.
на toHtml(Spanned, int) : оберните последовательные строки текста, разделенные ‘\n’ внутри
на toHtml(Spanned, int) : оберните каждую строку текста, разделенную ‘\n’ внутри
чтобы расширить ответ от @Rockney и @k2col, улучшенный код может выглядеть так:
разница в том, что нет дополнительной локальной переменной, и устаревание только в else филиала. Таким образом, это не будет подавлять весь метод, кроме одной ветви.
это может помочь, когда Google решит в некоторых будущих версиях Android, чтобы осудить даже fromHtml(String source, int flags) метод.
для подавления проверки только для одного оператора, но не для всего метода.
класс framework был изменен, чтобы потребовать флаг для информирования fromHtml() Как обрабатывать переносы строк. Это было добавлено в Нуге, и касается только проблемы несовместимости этого класса в разных версиях Android.
я опубликовал библиотеку совместимости для стандартизации и backport класса и включить больше обратных вызовов для элементов и стилей:
хотя он похож на Html-класс фреймворка, некоторые изменения подписи были необходимы, чтобы разрешить больше обратных вызовов. Вот пример со страницы GitHub:
или вы можете использовать androidx.core.text.HtmlCompat :
попробуйте следующее Для поддержки основных тегов html, включая теги ul ol li. Создайте обработчик тегов, как показано ниже
Установите текст действия, как показано ниже
и html-текст в строковых файлах ресурсов как
Источник
Html.fromHtml deprecated in Android N
Posted by: admin November 13, 2017 Leave a comment
I am using Html.fromHtml to view html in a TextView .
But Html.fromHtml is now deprecated in Android N+
What/How do I find the new way of doing this?
You have to add a version check and use the old method on Android M and below, on Android N and higher you should use the new method. 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.
Flag parameters:
You can read more about the different flags on the
Html class documentation
I had a lot of these warnings and I always use FROM_HTML_MODE_LEGACY so I made a helper class called HtmlCompat containing the following:
Compare of the flags of fromHtml().
This method was
deprecatedin API level 24.
You should use FROM_HTML_MODE_LEGACY
Separate block-level elements with blank lines (two newline
characters) in between. This is the legacy behavior prior to N.
Code
From official doc :
fromHtml(String) method was deprecated in API level 24. use fromHtml(String, int)
instead.
TO_HTML_PARAGRAPH_LINES_CONSECUTIVE Option for toHtml(Spanned, int) : Wrap consecutive lines of text delimited by ‘\n’ inside
TO_HTML_PARAGRAPH_LINES_INDIVIDUAL Option for toHtml(Spanned, int) : Wrap each line of text delimited by ‘\n’ inside a
or a
element.
Just to extend the answer from @Rockney and @k2col the improved code can look like:
Where the CompatUtils.isApiNonLowerThan :
The difference is that there are no extra local variable and the deprecation is only in else branch. So this will not suppress all method but single branch.
It can help when the Google will decide in some future versions of Android to deprecate even the fromHtml(String source, int flags) method.
to suppress inspection just for single statement but not the whole method.
If you are lucky enough to develop on Kotlin,
just create an extension function:
And then it’s so sweet to use it everywhere:
The framework class has been modified to require a flag to inform fromHtml() how to process line breaks. This was added in Nougat, and only touches on the challenge of incompatibilities of this class across versions of Android.
I’ve published a compatibility library to standardize and backport the class and include more callbacks for elements and styling:
While it is similar to the framework’s Html class, some signature changes were required to allow more callbacks. Here’s the sample from the GitHub page:
Try the following to support basic html tags including ul ol li tags.
Create a Tag handler as shown below
Set the text on Activity as shown below
Источник
Html.fromHtml deprecated in Android N
I am using Html.fromHtml to view html in a TextView .
But Html.fromHtml is now deprecated in Android N+
What/How do I find the new way of doing this?
Answers
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 .
This allows you to use:
You can read more about the different flags on the HtmlCompat-documentation
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.
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.
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.
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.
You can read more about the different flags on the Html class documentation
Источник
Android html fromhtml deprecated
7. FROM_HTML_SEPARATOR_LINE_BREAK_LIST: This flag is used to indicate that texts inside
- elements will be separated from other texts with one newline character by default.
8. FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM: This flag is used to indicate that texts inside
elements will be separated from other texts with one newline character by default.
9. FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH: This flag is used to indicate that inside
elements will be separated from other texts with one newline character by default.
Example 1 Of Parse HTML File content Using WebView With Example In Android Studio:
Below is the example of HTML in which we parse the HTML file and display the HTML content in our Android WebView. In this example firstly we create a assets folder and store a HTML file in it. After that we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadUrl() method we display the content in our webView.
Step 1: Create a new project and name it HtmlExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a WebView.
Step 3: Now create assets folder in App. You can read here how to create assets folder in Android Studio
Step 4: Now inside assets folder add a HTML file name myfile.html. You can read here how to add local html file in Android Studio. Also inside myfile.html add the below HTML content or add any content in HTML format.
Step 5: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content from file stored in assets folder into WebView.
Output:
Now run the App and you will see local content added in HTML file is loaded in Webview.
Example 2 Of HTML In Android Studio Using TextView:
Below is the example of HTML in which we display the HTML content in our Android TextView with the help of fromHtml() method. In this example firstly we create a TextView in our XML file and then get the reference of TextView in our MainActivity and finally with the help of fromHtml() method we set the content in our TextView.
Step 1: Create a new project and name it HtmlExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a TextView.
Step 3: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the TextView and then set the HTML content which is stored in a string variable into TextView using fromHtml() method.
Output:
Now run the App and you will see HTML content is shown in TextView.
Example 3 Of HTML content in WebView With Example in Android Studio:
Below is the example of HTML in which we display the HTML content in our Android WebView. In this example firstly we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadDataWithBaseURL() method we display the content in our webView.
Step 1: Create a new project and name it HtmlWebViewExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a WebView.
Step 3: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content which is stored in a string variable into WebView.
Output:
Now run the App and you will see HTML content is displayed using Webview.
Источник