在非主线程非MainActivity中更新Toast、ImageView等UI控件方法

首先需要明确一点就是UI只能在主线程中更新,其他地方想更新UI,我目前学到的有两种方法:
1.采用handler的方式

public class MainActivity extends Activity{
		......
		ImageView imageView;
		......
		protected void onCreate(Bundle savedInstanceState) {
			......
			imageView=(ImageView) findViewById(R.id.imageView_background);
		}
		......
		//调用imageShow就可以更新imageView
	    private void imageShow(Bitmap bitmap) {
              Message msg=new Message();
              msg.what=0;
              msg.obj=bitmap;
              handler.handleMessage(msg);
         }
        private Handler handler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                        case 0:
                            imageView.setImageBitmap((Bitmap) msg.obj);
                            break;
                        case 1:
                            break;
                }
        }
    };
}

2.将想要修改的UI名称放入方法的形参中,就可以在方法中修改UI,调用该方法就可以实现更新UI
(1)主线程中:

public class MainActivity extends Activity{
		......
		ImageView imageView;
		......
		protected void onCreate(Bundle savedInstanceState) {
				......
				imageView=(ImageView) findViewById(R.id.imageView_background);
				MyBitmapUtils myBitmapUtils=new MyBitmapUtils(imageView);//将imageView作为形参传递出去
		}
}

(2)在想要更新imageView的类MyBitmapUtils中

public class MyBitmapUtils {
		......
		ImageView imageView;
		......
		public MyBitmapUtils(ImageView imageView){
				this.mageView=mageView;
		}
		public void changeImageView(ImageView imageView,Bitmap image){
				imageView.setImageResource(res.drawable.image);//修改imageView
		}
		
		public void dosomething{
			//调用changeImageView就可以更改imageView
			hangeImageView(imageView , image1);
		}
}

你可能感兴趣的:(Android)