android异步更新UI
?android下面圖片更新是需要啟動(dòng)多個(gè)子線程來(lái)進(jìn)行的,而android下面是并不是線程安全的,所以thread這里是用不了的,只能用runnable接口。
廢話(huà)不多說(shuō)了 直接上代碼。
1、下載線程 ?繼承runnable接口
public class DownloadImage implements Runnable {
?
private ImageView p_w_picpathView;
private String p_w_picpathUrl;
private Bitmap bitmap;
?
?? ? ? ?//構(gòu)造的時(shí)候傳入要更新的ImageView ,同時(shí)傳入圖片的URL
public DownloadImage(ImageView p_w_picpathView, String p_w_picpathUrl) {
super();
this.p_w_picpathView = p_w_picpathView;
this.p_w_picpathUrl = p_w_picpathUrl;
}
public Handler handler = new Handler();
Runnable updateResults = new Runnable() {
?
@Override
public void run() {
updateUI();
}
};
public void run() {
HttpGet httpRequest = null;
URL url;
try {
url = new URL(p_w_picpathUrl);
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
? ? ? ? .execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
? ?bitmap = BitmapFactory.decodeStream(instream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.post(updateResults);
}
public void updateUI(){
p_w_picpathView.setImageBitmap(bitmap);
}
}
2、主程序
ImageView p_w_picpathView = (ImageView)findViewById(R.id.p_w_picpath);
String p_w_picpathUrl = "http://www.qqzhi.com/show/UploadPic/2010-5/2010521102357899.jpg";
?new Thread(new DownloadImage(p_w_picpathView, p_w_picpathUrl)).start();
這些添加在oncreate()里面就實(shí)現(xiàn)了圖片的更新了 ?
?
3、配置文件AndroidManifest
<uses-permission android:name="android.permission.INTERNET"/>
獲取訪問(wèn)網(wǎng)絡(luò)權(quán)限
?
4、布局文件
<ImageView
android:id="@+id/p_w_picpath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x = "100px"
android:layout_y = "100px"
android:src="@drawable/icon"
/>
?
?
OK,要實(shí)現(xiàn)的功能就完全實(shí)現(xiàn)了,你可以定義N個(gè)變量(就是你需要更新的圖片),目前我測(cè)試一次更新20幅消耗時(shí)間1s。
希望能對(duì)大家有所幫助,有興趣可以一起討論!
?
?
?
轉(zhuǎn)載于:https://blog.51cto.com/alloxa/499424
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的android异步更新UI的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: struts2的处理流程
- 下一篇: 电子商务公司的职能架构及基础岗位职能