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

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代码:

 

你可能感兴趣的:(Runnable)