android图片异步加载二之hadnler+message+runnable

本文展示了一个使用Android进行同步图片加载的例子。通过创建线程来加载不同URL的图片,并使用Handler将图片显示到对应的ImageView中。该方法适用于简单的图片加载场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class SyncLoadImg2 extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		loadImg("http://www.baidu.com/img/baidu_logo.gif",R.id.img1);
		loadImg("http://img3.cache.netease.com/www/logo/logo_png.png",R.id.img2);
		loadImg("http://www.iteye.com/images/logo.gif?1308833136",R.id.img3);
	}
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Drawable drawable = (Drawable) msg.obj;
			int id = msg.arg1;
			ImageView img = (ImageView)SyncLoadImg2.this.findViewById(id);
			img.setImageDrawable(drawable);
		}
	};
	
	private void loadImg(final String urlStr,final int id) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					Drawable drawable = ImgManager.getDrawableFromUrl(urlStr);
					Thread.currentThread().sleep(2000);
					Message msg = handler.obtainMessage();
					msg.obj = drawable;
					msg.arg1 = id;
					handler.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		};
		thread.start();
	}
}

 布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="图片开始位置"
    />
    <ImageView 
    	android:id="@+id/img1"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <ImageView 
    	android:id="@+id/img2"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <ImageView 
    	android:id="@+id/img3"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    />
    <TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="图片结束位置"
    />
</LinearLayout>

 

activity代码:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值