Android Development Series 8: how to mix images and text
In some Android applications, You need to insert an image in the middle of the text, such as the effect shown in the following figure:
The weather pictures are displayed behind the text. To achieve this effect, you can write a View, but you can also use TextView and android. text. Spanned to achieve this effect.
The Spanned content can be html text, and the image can be embedded with the img element. The image content can be obtained based on the src address of the img element, you can also load the src address from the local resource file saved on your mobile phone. The following is a simple sample code:
TextView weather = (TextView) findViewById (R. id. weather );
Spanned info = null;
Try
{
Info = getWeather (defaultCity );
}
Catch (Exception e ){
}
If (info! = Null ){
Weather. setText (info );
} Else {
Weather. setText ("An error occurred while obtaining weather information! ");
}
Spanned getWeather (String city ){
String weatherData; // weather information html segment
ImageGetter imgGetter = new Html. ImageGetter (){
@ Override
Public Drawable getDrawable (String url ){
Drawable drawable = null;
If (url. startsWith ("/")){
// The image url is a relative address and must be an absolute url address.
}
Byte [] imgBuffer = null;
Try {
// Obtain the image content from the url and save it in imgBuffer
} Catch (Exception e ){
Return null;
}
String name = "";
Int pos = url. lastIndexOf ("/");
Name = url. substring (pos + 1); // Image File name
InputStream in = new ByteArrayInputStream (imgBuffer );
Drawable = Drawable. createFromStream (in, name); // create a Drawable from the input stream
Try {
In. close ();
} Catch (IOException e ){
}
Return drawable;
}
};
Spanned text = null;
Try {
Text = Html. fromHtml (weatherData, imgGetter, null); // create a Spanned
} Catch (Exception e1 ){
Text = null;
}
Return text;
}
The code is relatively simple. If the image has been saved in a resource file, you do not need to download the image content from the Internet. You only need to use the Drawable. createFromResourceStream method to load it from the resource file to create a Drawable.