Cómo mostrar HTML en TextView?


Tengo simple HTML :

<h2>Title</h2><br>
<p>description here</p>

Quiero mostrar texto con estilo HTML en TextView. Cómo hacer esto?

Author: UMAR, 2010-01-22

18 answers

Necesita usar Html.fromHtml() para usar HTML en tus cadenas XML. Simplemente hacer referencia a una cadena con HTML en su diseño XML no funcionará.

Por ejemplo (

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

Por ejemplo (>= Android Nougat):

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));

Para distinguir entre las versiones de Android use Build.VERSION.SDK_INT >= Build.VERSION_CODES.N.

 1129
Author: Timo Bähr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-05 08:48:18

Echa un vistazo a esto: https://stackoverflow.com/a/8558249/450148

Es bastante bueno también!!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

Funciona solo para unas pocas etiquetas.

 59
Author: Felipe Micaroni Lalli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:50

SetText (Html.fromHtml (bodyData)) es obsoleto después de api 24. Ahora tienes que hacer esto:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
 } else {
      tvDocument.setText(Html.fromHtml(bodyData));
 }
 59
Author: Shohan Ahmed Sijan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-11 07:40:04

Si desea poder configurarlo a través de xml sin ninguna modificación en el código java, puede encontrar esta idea útil. Simplemente llama a init desde constructor y establece el texto como html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

Xml:

        <com.package.HTMLTextView
        android:text="@string/about_item_1"/>
 37
Author: user1299412,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-13 20:20:56

El siguiente código me dio el mejor resultado.

TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);
 21
Author: Rajiv Manivannan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-22 15:06:46

Si está intentando mostrar HTML desde un id de recurso de cadena, es posible que el formato no aparezca en la pantalla. Si eso le está sucediendo, intente usar etiquetas CDATA en su lugar:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

Ver este post para más detalles.

 16
Author: Phileo99,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:36
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
    SiteLink= (TextView) findViewById(R.id.textViewSite);
    SiteLink.setText(Html.fromHtml(value));
    SiteLink.setMovementMethod(LinkMovementMethod.getInstance());
 11
Author: Pedro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-02 13:15:45

Si solo desea mostrar un texto html y realmente no necesita un TextView, tome un WebView y utilícelo de la siguiente manera:

String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);

Esto tampoco le restringe a unas pocas etiquetas html.

 10
Author: prom85,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-26 13:51:38

Vale la pena mencionar que el método Html.fromHtml (String source) está obsoleto a partir del nivel de API 24. Si esa es tu API de destino, deberías usar Html.fromHtml (String source, int flags) en su lugar.

 10
Author: Teo Inke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-22 05:31:34

El mejor enfoque para usar secciones CData para la cadena en cadenas.archivo xml para obtener una visualización real del contenido html al TextView el siguiente fragmento de código le dará la idea justa.

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

La sección CData en string text mantiene los datos de la etiqueta html intactos incluso después de formatear el texto usando String.método de formato. Entonces, Html.fromHtml (str) funciona bien y verá el texto en negrita en el mensaje de bienvenida.

Salida:

Bienvenido, a su aplicación de música favorita almacenar. Iniciado sesión como: nombre de usuario

 10
Author: Rajendhiran Easu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-19 11:59:47

También me gustaría sugerir el siguiente proyecto: https://github.com/NightWhistler/HtmlSpanner

El uso es casi el mismo que el convertidor de Android predeterminado:

(new HtmlSpanner()).fromHtml()

Lo encontré después de que ya empecé por propia implementación de html al convertidor spannable, porque Html estándar.fromHtml no proporciona suficiente flexibilidad sobre el control de renderizado e incluso ninguna posibilidad de usar fuentes personalizadas de ttf

 6
Author: Fedotchenco Denis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-12 08:15:43

Uso simple Html.fromHtml("html string"). Esto funcionará. Si la cadena tiene etiquetas como <h1> entonces vendrán espacios. Pero no podemos eliminar esos espacios. Si aún desea eliminar los espacios, puede eliminar las etiquetas en la cadena y luego pasar la cadena al método Html.fromHtml("html string"); . También generalmente estas cadenas vienen del servidor (dinámico) pero no a menudo, si es el caso mejor pasar la cadena como es al método que tratar de eliminar las etiquetas de la cadena.

 5
Author: nole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-11 00:01:09
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
 4
Author: samuel gildas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-27 12:40:40

He implementado esto usando la vista web. En mi caso tengo que cargar la imagen de la URL junto con el texto en la vista de texto y esto funciona para mí.

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
 3
Author: Killer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-04 11:18:34

Se ha sugerido a través de varias respuestas usar la clase de marco Html como se sugiere aquí, pero desafortunadamente esta clase tiene un comportamiento diferente en diferentes versiones de Android y varios errores sin abordar, como se demuestra en issues 214637, 14778, 235128 y 75953.

Por lo tanto, es posible que desee utilizar una biblioteca de compatibilidad para estandarizar y retroportar la clase Html a través de las versiones de Android que incluye más devoluciones de llamada para elementos y estilo:

Proyecto Github HtmlCompat

Aunque es similar a la clase Html del framework, 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);
 2
Author: Paul Lammertsma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-15 08:26:02

Cada vez que escriba la vista de texto personalizada, la función básica de texto conjunto de HTML se desvanecerá de algunos de los dispositivos.

Así que tenemos que hacer los siguientes pasos adicionales hacer es trabajo

La clase pública CustomTextView extiende TextView {

/ / Inside constructor

   setText(Html.fromHtml(getText().toString()));

}

 2
Author: Vinayak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 06:10:49

Haga un método global como:

public static Spanned stripHtml(String html) {
            if (!TextUtils.isEmpty(html)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
                } else {
                    return Html.fromHtml(html);
                }
            }
            return null;
        }

También puedes usarlo en tu Actividad / Fragmento como:

text_view.setText(stripHtml(htmlText));
 0
Author: Shylendra Madda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 16:39:24

Puedo sugerir una solución un tanto hacky pero todavía genio! Tengo la idea de este artículo y lo adapté para Android. Básicamente utilizas un WebView e insertas el HTML que quieres mostrar y editar en una etiqueta div editable. De esta manera cuando el usuario toca el WebView aparece el teclado y permite la edición. Solo tienes que añadir un poco de JavaScript para volver el HTML editado y listo!

Aquí está el código:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

Y aquí es el componente como un Gist.

Nota: I no necesitaba la devolución de llamada de cambio de altura de la solución original, por lo que falta aquí, pero puede agregarla fácilmente si es necesario.

 0
Author: AXE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-27 07:10:30