Android更新UI的五种方式

  • handler.post
  • activity.runOnUiThread
  • view.post
  • handler+Thread
  • AsyncTask

例子:

package com.chao.updateui;



import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;



import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.TextView;



public class MainActivity extends Activity implements OnClickListener{

    private Layout layout;

    private Handler handler;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        initLayout();

        initValue();

    }

    

    private void initLayout(){

        layout=new Layout();

        layout.helloText=(TextView) findViewById(R.id.helloText);

        layout.webImg=(ImageView) findViewById(R.id.webImg);

        layout.button1=(Button) findViewById(R.id.button1);

        layout.button2=(Button) findViewById(R.id.button2);

        layout.button3=(Button) findViewById(R.id.button3);

        layout.button4=(Button) findViewById(R.id.button4);

        layout.button5=(Button) findViewById(R.id.button5);

        layout.button1.setOnClickListener(this);

        layout.button2.setOnClickListener(this);

        layout.button3.setOnClickListener(this);

        layout.button4.setOnClickListener(this);

        layout.button5.setOnClickListener(this);

    }

    

    private void initValue(){

        layout.button1.setText("1.Handler.post");

        layout.button2.setText("2.activity.runOnUiThread");

        layout.button3.setText("3.view.post");

        layout.button4.setText("4.handler+Thread");

        layout.button5.setText("5.AsyncTask");

    }

    

    private class Layout{

        TextView helloText;

        ImageView webImg;

        Button button1;

        Button button2;

        Button button3;

        Button button4;

        Button button5;

    }



    //1.Handler.post

    private void method_1(){

        new Handler().postDelayed(new Runnable() {

            

            @Override

            public void run() {

                layout.helloText.setText("Handler的postDelayed延时一秒");

            }

        }, 1000);

    }

    //2.activity.runOnUiThread

    private void method_2(){

        new Thread(new Runnable() {

            

            @Override

            public void run() {

                try {

                    Thread.sleep(1000);

                    runOnUiThread(new Runnable() {

                        

                        @Override

                        public void run() {

                            layout.helloText.setText("在子线程中使用activity.runOnUiThread");

                        }

                    });

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }).start();

    }

    //3.view.post

    private void method_3(){

        new Thread(new Runnable() {

            

            @Override

            public void run() {

                try {

                    Thread.sleep(1000);

                    layout.helloText.post(new Runnable() {

                        

                        @Override

                        public void run() {

                            layout.helloText.setText("在子线程中使用TextView.post");

                        }

                    });

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }).start();

    }

    //4.Handler+Thread

    private void method_4(){

        handler=new Handler(){

            @Override

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                if(msg.what==1){

                    Bundle bundle=msg.getData();

                    String name=bundle.getString("name");

                    String sex=bundle.getString("sex");

                    String age=bundle.getString("age");

                    layout.helloText.setText(name+"\n"+sex+"\n"+age);

                }

            }

        };

        Thread thread=new Thread(new Runnable() {

            

            @Override

            public void run() {

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                Message msg=Message.obtain();

                msg.what=1;

                

                Bundle bundle=new Bundle();

                bundle.putString("name", "张三");

                bundle.putString("sex", "男");

                bundle.putString("age", "16");

                msg.setData(bundle);

                

                handler.sendMessage(msg);

            }

        });

        thread.start();

    }

    //5.AsyncTask

    private void method_5(){        

        AsyncTask<String, Integer, Bitmap> async=new AsyncTask<String, Integer, Bitmap>(){

            @Override

            protected Bitmap doInBackground(String... params) {

                publishProgress(0);

                HttpClient client = new DefaultHttpClient();

                HttpGet get = new HttpGet(params[0]);

                publishProgress(30);

                final Bitmap bitmap;

                try {

                    HttpResponse response = client.execute(get);

                    bitmap = BitmapFactory.decodeStream(response.getEntity()

                            .getContent());

                } catch (Exception e) {

                    return null;

                }

                publishProgress(100);

                return bitmap;

            }

            @Override

            protected void onProgressUpdate(Integer... values) {

                super.onProgressUpdate(values);

                layout.helloText.setText("进度-"+values[0]+"%");

            }

            @Override

            protected void onPostExecute(Bitmap result) {

                super.onPostExecute(result);

                if(result==null){

                    layout.helloText.setText("获取图片失败");

                }else{

                    layout.helloText.setText("获取图片成功");

                    layout.webImg.setImageBitmap(result);

                }

            }

            @Override

            protected void onPreExecute() {

                layout.webImg.setImageBitmap(null);

            }

            

        };        

        async.execute("http://imgsize.ph.126.net/?imgurl=http://img2.ph.126.net/-RloZHuMn-ultOW_YDF5fQ==/"

                + "6608648723609095427.jpg_96x96x0x90.jpg");        

    }





    @Override

    public void onClick(View v) {

        switch(v.getId()){

        case R.id.button1:

            method_1();

            break;

        case R.id.button2:

            method_2();

            break;

        case R.id.button3:

            method_3();

            break;

        case R.id.button4:

            method_4();

            break;

        case R.id.button5:

            method_5();

            break;

        default:

            break;

        }

    }

}
MainActivity.java

 

完整demo:http://pan.baidu.com/s/1eQcUV0Q

你可能感兴趣的:(android)