studio permisos nougat ejemplos descargar apis android deprecated android-7.0-nougat

permisos - Html.fromHtml en desuso en Android N



firmware android 7.0 descargar (13)

Estoy usando Html.fromHtml para ver html en un TextView .

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

Pero Html.fromHtml ahora está en desuso en Android N +

¿Qué / Cómo encuentro la nueva forma de hacer esto?


Aquí está mi solució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())); }


Comparación de las banderas de 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


Del documento oficial:

fromHtml(String) quedó en desuso en el nivel 24 de API. Utilice fromHtml(String, int) lugar.

  1. TO_HTML_PARAGRAPH_LINES_CONSECUTIVE Opción para toHtml(Spanned, int) : toHtml(Spanned, int) líneas consecutivas de texto delimitadas por ''/n'' dentro de los elementos <p> .

  2. TO_HTML_PARAGRAPH_LINES_INDIVIDUAL Opción para toHtml(Spanned, int) : toHtml(Spanned, int) cada línea de texto delimitada por ''/n'' dentro de un elemento <p> o <li> .

https://developer.android.com/reference/android/text/Html.html


La clase de marco se ha modificado para requerir un indicador que informe desde fromHtml() cómo procesar saltos de línea. Esto se agregó en Nougat, y solo toca el desafío de las incompatibilidades de esta clase en todas las versiones de Android.

He publicado una biblioteca de compatibilidad para estandarizar y respaldar la clase e incluir más devoluciones de llamada para elementos y estilo:

https://github.com/Pixplicity/HtmlCompat

Si bien es similar a la clase Html del marco, se requirieron algunos cambios de firma para permitir más devoluciones de llamada. Aquí está la muestra de la página de GitHub:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0); // You may want to provide an ImageGetter, TagHandler and SpanCallback: //Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0, // imageGetter, tagHandler, spanCallback); textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setText(fromHtml);


O puede usar androidx.core.text.HtmlCompat :

HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)

Documentos HTML Compat


Pruebe lo siguiente para admitir etiquetas html básicas, incluidas las etiquetas ul ol li. Cree un controlador de etiquetas como se muestra a continuación

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; } } } } }

Establezca el texto en Actividad como se muestra a continuación

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

Y texto html en archivos de cadena de recursos como

<! [CDATA [... datos html sin procesar ...]]>


Puedes usar

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

para suprimir la inspección solo para una sola declaración pero no todo el método.


Si estás usando Kotlin , lo logré usando una extensión de Kotlin:

fun TextView.htmlText(text: String){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)) } else { setText(Html.fromHtml(text)) } }

Entonces llámalo como:

textView.htmlText(yourHtmlText)


Si tiene la suerte de desarrollar en Kotlin, simplemente cree una función de extensión:

fun String.toSpanned(): Spanned { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY) } else { @Suppress("DEPRECATION") return Html.fromHtml(this) } }

Y luego es tan dulce usarlo en todas partes:

yourTextView.text = anyString.toSpanned()


Solo para extender la respuesta de @Rockney y @ k2col, el código mejorado puede verse así:

@NonNull public static Spanned fromHtml(@NonNull String html) { if (CompatUtils.isApiNonLowerThan(VERSION_CODES.N)) { return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { //noinspection deprecation return Html.fromHtml(html); } }

Donde el CompatUtils.isApiNonLowerThan :

public static boolean isApiNonLowerThan(int versionCode) { return Build.VERSION.SDK_INT >= versionCode; }

La diferencia es que no hay una variable local adicional y la desaprobación está solo en la rama else . Por lo tanto, esto no suprimirá todos los métodos excepto una rama.

Puede ayudar cuando Google decida en algunas versiones futuras de Android desaprobar incluso el fromHtml(String source, int flags) .


Tenía muchas de estas advertencias y siempre uso FROM_HTML_MODE_LEGACY, así que hice una clase auxiliar llamada HtmlCompat que contiene lo siguiente:

@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); } }


actualización : como mencionó @Andy, Google ha creado HtmlCompat que se puede usar en lugar del método siguiente. Agregue esta implementation ''androidx.core:core:1.0.1 dependencia implementation ''androidx.core:core:1.0.1 al archivo build.gradle de su aplicación. Asegúrese de utilizar la última versión de androidx.core:core .

Esto le permite usar:

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

Puede leer más acerca de los diferentes indicadores en la HtmlCompat-documentation

respuesta original: en Android N introdujeron un nuevo método Html.fromHtml . Html.fromHtml ahora requiere un parámetro adicional, llamado flags. Esta bandera te da más control sobre cómo se muestra tu HTML.

En Android N y superior, debe usar este nuevo método. El método anterior está en desuso y puede eliminarse en las futuras versiones de Android.

Puede crear su propio método Util que utilizará el método anterior en versiones anteriores y el método más nuevo en Android N y superior. Si no agrega una versión, verifique que su aplicación se rompa en las versiones inferiores de Android. Puede usar este método en su clase Util.

@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); } }

Puede convertir el HTML.FROM_HTML_MODE_LEGACY en un parámetro adicional si lo desea. Esto le da más control sobre qué bandera usar.

Puede leer más sobre los diferentes indicadores en la documentación de la clase Html


fromHtml

Este método fue desaprobado en el nivel 24 de API .

Debes usar FROM_HTML_MODE_LEGACY

Elementos separados a nivel de bloque con líneas en blanco (dos caracteres de nueva línea) en el medio. Este es el comportamiento heredado anterior a N.

Código

if (Build.VERSION.SDK_INT >= 24) { etOBJ.setText(Html.fromHtml("Intellij /n Amiyo",Html.FROM_HTML_MODE_LEGACY)); } else { etOBJ.setText(Html.fromHtml("Intellij /n Amiyo")); }

Para Kotlin

fun setTextHTML(html: String): Spanned { val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(html) } return result }

Llamada

txt_OBJ.text = setTextHTML("IIT Amiyo")