Android開發系列八:怎麼混合顯示圖片和文本

來源:互聯網
上載者:User
Android開發系列八:怎麼混合顯示圖片和文本

在有的Android應用中,需要在文字的中間插入一個圖片,比如像下面圖中所示的效果:

天氣小圖片顯示在文字的後面,要實現此效果可以自己寫一個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即可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.