Extview is not only string-based. We usually call the Public final void settext (charsequence text) method when passing the string parameter to the settext () method, the string class is a subclass of charsequence.
There are many charsequence sub-classes. One of them is spanned, which is similar to HTML text with tags. We can use it to display HTML in textview (Naturally, there are many HTML tags that are not supported, and only some of them are supported ).
A Method of the android. Text. html class:
[Java]
View plaincopyprint?
- Public static spanned fromhtml (string source)
HTML code can be converted to spanned.
[Java]
View plaincopyprint?
- Html = "
- + "<P> This text is normal </P>"
- + " ";
- Spanned sp = html. fromhtml (HTML );
- Textview. settext (HTML );
Display Effect:
It can be seen that the font effect is basically displayed, but the image is not displayed.
To display images, another reconstruction method of HTML. fromhtml must be used:
Public static spanned fromhtml (string source, HTML. imagegetter, HTML. taghandler)
Here, HTML. imagegetter is an interface. We need to implement this interface. Only the drawable object of the image can be returned in its getdrawable (string source) method.
Modified code:
[Java]
View plaincopyprint?
- Spanned sp = html. fromhtml (HTML, new HTML. imagegetter (){
- @ Override
- Public drawable getdrawable (string source ){
- Inputstream is = NULL;
- Try {
- Is = (inputstream) new URL (Source). getcontent ();
- Drawable d = drawable. createfromstream (is, "src ");
- D. setbounds (0, 0, D. getintrinsicwidth (),
- D. getintrinsicheight ());
- Is. Close ();
- Return D;
- } Catch (exception e ){
- Return NULL;
- }
- }
- }, Null );
- Textview. settext (SP );
It seems complicated, but in fact, the second parameter of fromhtml () is an anonymous class used for obtaining images.
Where
[Java]
View plaincopyprint?
- Is = (inputstream) new URL (Source). getcontent ();
- Drawable d = drawable. createfromstream (is, "src ");
It is used to obtain the corresponding drawable instance through the image address.
Because images of network resources are used, you must add the following permissions to the mainifest file:
[HTML]
View plaincopyprint?
- <Uses-Permission Android: Name = "android. Permission. Internet"/>
Modified running result:
The image is displayed normally.