圖片和文字的混合顯示

天氣小圖片顯示在文字的後面,要實現此效果可以自己寫一個View,但是也可以使用TextView結合android.text.Spanned來實現此效果。

Spanned的內容可以是一段html文本,圖片就可以用img元素嵌入進去了,圖片的內容可以根據img元素的src地址獲取,也可以根據此src地址從保存在手機本地的資源文件里加載。下面是簡單的示例代碼:

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("獲取天氣信息失敗!");
}
Spanned getWeather(String city) {
    String weatherData;//天氣信息html片段    
    ImageGetter imgGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String url) {
            Drawable drawable = null;
             if (url.startsWith("/")) {
                //圖片url地址是個相對地址,需要變成絕對url地址
             }
             byte[] imgBuffer = null;
             try {
                //從網址url獲取圖片內容,保存在imgBuffer裏
             } catch (Exception e) {
                 return null;
             }
             String name = "";
             int pos = url.lastIndexOf("/");
             name = url.substring(pos + 1);//圖片文件名
             InputStream in = new ByteArrayInputStream(imgBuffer);
             drawable = Drawable.createFromStream(in, name);//從輸入流創建Drawable        
             try {
                in.close();
             } catch (IOException e) {
             }                
            return drawable;
        }
    };
    Spanned text = null;
    try {
        text = Html.fromHtml(weatherData, imgGetter, null);//創建一個Spanned
    } catch (Exception e1) {
        text = null;
    }
    return text;
}

代碼比較簡單。如果圖片事先已經保存在資源文件裏,那麼就無需從網上去下載圖片內容了,只需使用Drawable.createFromResourceStream這個方法從資源文件加載進來創建Drawable即可。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章