Como mostrar imagen img scr en formato HTML con fromHTML

14 marzo, 2012 por Gonzalo de Córdoba Dejar una respuesta »

Objetivo:

Mostrar una imagen usando fromHTML, de forma que podremos cogerla de una internet con la etiqueta img de HTML.

Antes de este tutorial, aunque muy básico, puede que desees familiarizarte con fromHTML. Para ello puedes pasarte por un ejemplo en el que sólo se utiliza texto en HTML en este tutorial. En él se muestra el hipertexto en un AlertDialog, pero es igualmente sencillo asignarlo a un TextView.

Cuando deseamos utilizar HTML en un TextView, por ejemplo, podemos llamar al paquete android.text.html, dejando que él actúe sobre nuestro texto, aplicando la vista indicadas en las etiquetas que le dan formato. En este HTML podemos incluso utilizar llamadas a imágenes con la tag img src.

Creamos  mini-aplicación para coger el HTML y lo aplicamos a un TextView para mostrarlo. Para ello, debemos crear una aplicación desde el principio,  crear un TextView para insertar el hipertexto en HTML (con imagen incluida en este caso), y finalmente llamar a la clase android.text.html. Para que las imágenes en el HTML aparezcan debemos implementar la función getImageHTML, que devolverá una instancia de la clase ImageGetter, necesaria para ello.

Vemos una captura de la mini-aplicación:

Imagen en fromHTML by TutorialAndroidcom

Y a continuación mostramos el texto comentado:

Código fuente Java:

package fromHtml.image.tutorialandroid.com;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.widget.TextView;

public class HtmlFromHtmlImageActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String html = "Tus ejemplos en<br/>TutorialAndroid.com<br/><br/><img src='http://www.tutorialandroid.com/tutorialandroidcom.jpg' />";

      	Spanned s = Html.fromHtml(html,getImageHTML(),null);
        TextView txt = (TextView)findViewById(R.id.main_menu_textview);
      	txt.setText(s);
    }

    public ImageGetter getImageHTML(){
    	 ImageGetter ig = new ImageGetter(){
        	 public Drawable getDrawable(String source) {
        	  try{
        	   Drawable d = Drawable.createFromStream(new URL(source).openStream(), "src name");
        	   d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight());
        	   return d;
        	  }catch(IOException e){
        	   Log.v("IOException",e.getMessage());
        	   return null;
        	  }
        	 }
        	};
        return ig;
    }

}

Descárgate el código aquí

En el código descargable se encuentra el proyecto completo.

¡Espero que os sirva de ayuda, sobre todo a ti Ricardo Klein!

¡Saludos!

Publicidad

17 comentarios

  1. Ricardo Klein dice:

    Super!!!! Busqué ene en internet y no pude encontrar algo que me funcionara. Este código funciona a las mil maravillas.
    Ahora, no se si será mucho pedir pero, se podrá modificar para que en vez de tomar la imagen de internet la tome de asset o de res/drawable-hdpi.

    • Buenas Ricardo!
      pues simplemente tendríamos que cambiar la funcion ImageGetter:

      public ImageGetter getImageHTML(){
          	 ImageGetter ig = new ImageGetter(){
              	 public Drawable getDrawable(String source) {     	   
             		    int resID = getResources().getIdentifier(source, "drawable", "fromHtml.image.tutorialandroid.com"); //nombre del paquete al final
             		   Drawable d = new BitmapDrawable( BitmapFactory.decodeResource( HtmlFromHtmlImageActivity.this.getBaseContext().getResources(), resID));
              	   d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight());
              	   return d;
              	 }
              	};
              return ig;	
          }
      

      Y ahora en onCreate simplemente tendras la siguiente linea:

      String html = "Tus ejemplos en<br/>TutorialAndroid.com<br/><br/><img src='icon' />";
      

      Donde ‘icon’ es el nombre de la imagen que tengo en el directorio: drawable-hdpi/icon.png
      Espero que te sirva.
      Saludos!

      • Ricardo Klein dice:

        Nada que decir. No se como agradecerte. Funcionó a la perfección.

        • Kana dice:

          Does the style attribute works?I have a text that was retaecd using Html.fromHtml(htmlString), but once its rendered, it has an underline.Any idea on how to remove the underline?Thanks.

      • Nanda dice:

        I’d first check whether it’s inuerldned because of a link or a pair of u tags (or some other reason). You may have to modify the Spanned that is returned from the Html.fromHtml() call (or modify the HTML being passed to that beforehand).

  2. Diego dice:

    Hola amigos bueno quisiera agradecerles sobre los tutos que hacen que son de mucha ayuda para los que empezamos a programar en android.
    Tengo una consulta estaba observando sobre el Articulo de la Clase AsyncTask y tengo una duda sobre ese tema. Mi duda es la siguiente ahi tu le das un valor maximo de 1400000 al progressDialog y que valla aumentando de uno en uno el progressDialog hasta que llegue a 1400000 pero mi duda es la siguiente yo tengo un login en Android con Conexion a Pagina web y cuando lleno mi formulario del login y doy click en aceptar, empieza a ejecutar el codigo pero al dar click en el boton se pone como la pantalla como un poco lento osea creo que tiene un tiempo que se demora en comunicarse con la pagina web y hacer la consulta con la BD de la pagina web y verificar si existe el usuario o no. Mi duda es la siguiente como yo calculo el tiempo que se demora en hacer la consulta a la pagina web con Conexion a Base de Datos, para asi yo poner un progressDialog y ya no darle 1400000 sino el tiempo que he calculado en consultar a la Pagina web con Base de Datos. Gracias de antemano espero su pronta respuesta. Saludos desde PERU.

  3. Franco dice:

    Muy bueno el el tutorial, funciona muy bien. ¿Me podrías decir como debería hacer para que me muestre una imagen que esta en la memoria interna del teléfono? por ejemplo en data/data/fromHtml.image.tutorialandroid.com/files
    Muchas gracias de antemano.

  4. Freriutty dice:

    rolex watches writers are currently being hyped within the US, not only Western world Wonder post on rolex watches that the industry experts don’t want you to know. replica watches Compact study aids you with the most important inner workings for rolex watches in addition to what you want to perform right away. Rumors which experts state rolex watches takes to a shut, here are the follow-up mulberry bags rolex watches Fake photos – – A Fantastic rolex watches ‘cheat’ By which Fools 88% of the shoppers Probably the most joy you could have without leaving out rolex watches
    Never forget Each time You Could quite easily get a new rolex watches 100 % free, But You Decided not to?? Everything you do not realize regarding rolex watches can be costing much more than you think. replica watches Something you haven’t heard of rolex watches could very well be costing much more than you may think. rolex watches Today Obtainable in Thai and Italian! mulberry handbags The Sluggish Male’s Path To The rolex watches Triumph Essentially The Most Detailed rolex watches Tutorial You Ever Read Or Your Money Back

  5. AttedeAudinge dice:

    锘?
    My friends and i certainly disagree along with you attached to numerous development. Even thoughjfigh cheap Ugg Boots ,
    I do discover how one more will show up coming from some kind of Ugg boot trunk and as well , envision «Huh, that can only be odd ,» strange doesn’t suggest hideous. We believe to become underplaying the most significant ability in Uggs: COMFORT. The quantity of relieve might be so the highest you do not in fact like to see looks like plus start looking a lot of beautiful for your lower limb seriously trying to find lovely.

    Seriously envision may possibly be awfully and furthermore worthwhile of nearly every single any amount of money. Guys might eliminate the company’s two feet, specially in the winter.

    Card shoe items really should in acquiring an item which is actually snazzy coupled with decent. Because i envision Ugg boot, I know comfortableness segment, however they are don’t ever attractive towards the total eye. Is shortage curve in addition system while you are feeling distressed will most certainly be over-bearing inside your extremities. They create customers feel too muchlggcp Ugg Boots Outlet ,
    bigger than they will really normally. As well appears as if in case you sporting these boots with all of the break free all unavoidable Uggs shuffle. Will, what individuals insurance firm ? decide to put on making Ugg boot assist them to physical appearance far worse. Executes almost any person to reflect upon Uggs associated with shorts trends?

    In all honesty, that this Simple yet perfect Ugg sheepskin boots boot are nasty. Yep, might be pleased pleasant but that is within the only appeal to which they give. An advancedpwkiq cheap Ugg Boots ,
    name brand highbrow may possibly OK and there is many other techniques from Ugg sheepskin boots which could be snow organised. Stated, could possibly be moderately costly. Don’t fret even when, purely because Ugg boot aren’t going to be definitely the onlygkixm Ugg Boots Outlet ,
    sandals on the market. If you should spend some time going shopping you will be certain secure hiking footwear who definitely are happy even more popular with a person’s eye.

    People establish approximately tells the whole works Ugg sheepskin boots. Although Ugg boot brand spanking constitutes a quantity of boots and shoesuvwdd Ugg Boots Outlet ,
    (1 of the parties atrocious), from the most traditionally used feel is the only Simple yet perfect Uggs boots or shoes. Sporting when day starts to relax and others start trading their particular shorts not to mention summer best for a lot of and thusiqhty Ugg Boots Outlet ,
    brings together, My organization is nearly always mixed-up on the quantity of adult men and women cling back to the UGGs.

  6. Freriutty dice:

    Bored With rolex watches ?? Then check this out!! Researcher Detects High-risk rolex watches fixation Louis Vuitton Handbags Outlet What the specialists are typically not saying surrounding rolex watches as well as how this is affecting you. My New-found rolex watches application Work While You Take a nap! ! Louis Vuitton Handbags Outlet rolex watches Replicas . . . Ideal rolex watches trick Which experts claim Fools 87.5% of the end-users Exactly why almost everything you have learned about rolex watches is drastically wrong and exactly what you need understand.
    Quick review helps you with some of the intricacies for rolex watches and exactly what you ought to do right away. Recall When You Could really easily get the new rolex watches completely free, And You Still did not?? Fake Louis Vuitton Bags The Slack Man’s Secret To The rolex watches Success rolex watches Counterfeits – Perfect rolex watches trick Of which Fools 97% of the shoppers replica handbags rolex watches-lady has tried contemporary strategy . . . steps to make a king’s ransom from nothing A Lazy Man’s Route To The rolex watches Triumph

  7. Freriutty dice:

    Personal information rolex watches which only the pro’s were aware about. Destroy rolex watches Pains Definately replica watches Right Here Is A Technique That Is Actually Assisting rolex watches-industry professionals To Improve A new rolex watches google search Dash board widget mulberry bags rolex watches is given 100 % free supercharge… from a civic activity ensemble! The Spectacular Innovative rolex watches methods Noticed By My Girlfriend
    Your Actual Key For rolex watches rolex watches brings spanking new lifespan into an old matter. . . gold set replica designer handbags Specifically why noone is referfing to rolex watches and as an outcome precisely what one should do right away. rolex watches is getting fully free boost… by a civic exercise sector!! replica watches The Incredible Innovative new rolex watches blueprint Picked up By My Best Friend The reasons no company is dealing with rolex watches and exactly what you should take care of as we speak.

  8. Fertiapinna dice:

    Taurus children may hide their feelings Suh Jersey until provoked. Teaching emotional control may help foster better emotional sensitivity in young Taureans. Taurus children love beauty and harmony and loathe disorganization. Finally, the bank notes took a flyer on an intriguing DT prospect. Michael Jasper may be a 6’4″, 385 lbs. defensive lineman who actually played at 430 lbs.
    Most basketball fans recall Tyrone Curtis Bogues learning to be a cute and huggable ambassador of http://www.packers-shop.com/21_Charles_Woodson it, however the truth is until this 5 spark plug grew up from just one of Brandon Marshall Jersey Baltimore most dangerous housing projects and saw his father carted off to the clink with the armed robbery charge while he was only 12. «I spent your childhood years as hard as you can get it,» Bogues told Sports Illustrated years later. «I wasn pleased with what my pops did, nevertheless guess fix your vision . he felt that’s his only approach of survival.» That have, and also the his diminutive size led to Bogues usually to be the dirtiest and several physical player on the court.

    Find More information:

    http://ekstasisdance.com/community/topic.php?id=233398&replies=1#post-261046
    http://www.glorchluainin.com/bbpress/topic.php?id=146471&replies=1#post-155286
    http://edu.cpg.se/se08298/public_html/wiki4/node/61028
    http://cmsafc.org/forum/topic.php?id=110375&replies=1#post-130972
    http://cisumboards.informe.com/viewtopic.php?p=6917#6917

  9. Fertiapinna dice:

    When a thinking Stafford Jersey of simply spicing up something simple just like your tv room try out terry cullen mental performance. There is reason you’ve got to hire an enclosed decorator who charges thousands Matt Forte Jersey of dollars to achieve in addition Matt Forte Jersey that anyone can do. Seek for accessories that is designed to complement your flooring, wall and furniture color scheme.
    We’ll have an overabundance upon the team’s plans in his absence looking for the main released. It’s important to note that Muhsin Muhammad’s 22-yard TD catch today was the 1st time all season that any wide receiver except Smith having a TD reception for this Panthers..
    Mark don grab it twisted Irrrm a sucker for Chad and what he did within the Dolphins but our success that year scaled like a number of easiest schedules with the league and in addition the gimmick in the wildcat that took longer for teams to adjust to. We cant have faith in retread Manning doing the exact magic as that season and the still not answer our Prolonged needs! I seen all morning the argument that you build teams for 4 or 5 years. But the truth is can honestly indicate that discover teams like Colonial and Pittsburgh that appear to hold made the playoffs for the yearly basis..

    Other Information about This Articles:

    http://balagh.org/?p=83424
    http://gnc.org.au/forum/topic.php?id=136020&replies=1#post-148855
    http://ocgt.com/ocgt/groups/globalization-is-no-longer-a-theory-qiukaikai1108/
    http://sanwango.com/node/10197
    http://revtc.com/Forum/forum_posts.asp?TID=18966&PID=25230#25230

  10. Mauricio dice:

    Estupendo tutorial.

    Como puedo añadir el evento touch a la imagen para llamar otro activity por ejemplo?

    Gracias!

  11. Angel dice:

    Alguien sabe si es posible agregar emoticones personalizados a un teclado Android?

Trackbacks /
Pingbacks

  1. airmax trainers

Deja un comentario

Rellena el captcha please!! *

Uso de cookies

Este sitio web utiliza cookies para que usted tenga la mejor experiencia de usuario. Si continúa navegando está dando su consentimiento para la aceptación de las mencionadas cookies y la aceptación de nuestra política de cookies, pinche el enlace para mayor información.

ACEPTAR
Aviso de cookies