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

时间: 2024-07-28 16:43:12

Android更新UI的五种方式的相关文章

Android更新UI的四种方式

前言 相信初学Android开发的朋友来说,应该都会遇到一个问题,我们开启了一个线程,在这个线程里面我们进行了更新UI的操作,也许是在TextView显示了一行文字,也许是改变了ImageView显示的图片,虽然只是看似简单并且正确的操作,但是Android系统让你的程序光荣的崩溃了,并且你还不知道为什么错,这才是最痛苦的,曾经深受这种痛苦的我,为了不再让这种痛苦蔓延下去,我决定把更新UI的几种方法给大家好好说说,让大家在Thread的run方法中可以随心所欲的更新UI,再也不用痛苦了. 实现

Android 更新UI的几种方式

1.Activity的 runOnUiThread textView = (TextView) findViewById( R.id.tv ); new Thread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText( "更新UI了"); } }); } }).start(); andro

Android攻城狮 Android中更新UI的几种方式

Android中更新UI的几种方式: 1. Activity 的 runOnUiThread() 2. Handler 的 post() 3. Handler 的 sendMessage() 4. View 的 post() 1 public class FiveActivity extends Activity { 2 3 private TextView textView; 4 5 private Handler handler = new Handler() { 6 public void

探讨android更新UI的几种方法

作为IT新手,总以为只要有时间,有精力,什么东西都能做出来.这种念头我也有过,但很快就熄灭了,因为现实是残酷的,就算一开始的时间和精力非常充足,也会随着项目的推进而逐步消磨殆尽.我们会发现,自己越来越消极怠工,只是在无意义的敲代码,敲的还是网上抄来的代码,如果不行,继续找. 这就是项目进度没有规划好而导致的. 最近在做有关蓝牙的项目,一开始的进度都安排得很顺利,但是因为测试需要两部手机,而且还要是android手机,暑假已经开始了,同学们都回家了,加上我手机的蓝牙坏了,导致我的进度严重被打乱!而

Android 更新UI的两种方法——handler和runOnUiThread() - $firecat的代码足迹$ - 博客频道 - CSDN.NET

文章来源:http://www.2cto.com/kf/201302/190591.html Android 更新UI的两种方法——handler和runOnUiThread() 在Android开发过程中,常需要更新界面的UI.而更新UI是要主线程来更新的,即UI线程更新.如果在主线线程之外的线程中直接更新页面显示常会报错.抛出异常:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread th

Android 更新UI的两种方法——handler和runOnUiThread(

Android 更新UI的两种方法——handler和runOnUiThread() 在Android开发过程中,常需要更新界面的UI.而更新UI是要主线程来更新的,即UI线程更新.如果在主线线程之外的线程中直接更新页面显示常会报错.抛出异常:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

Android更新Ui的几种方法和见解

<代码里的世界> 用文字札记描绘自己 android学习之路 转载请保留出处 by Qiao http://blog.csdn.net/qiaoidea/article/details/45115047 1. 简述 先贴一个我们刚做Android开发时候最容易遇到的一个错误异常 AndroidRuntimeException :"Only the original thread that created a view hierarchy can touch its views&quo

探讨android更新UI的几种方法(转)

作为IT新手,总以为只要有时间,有精力,什么东西都能做出来.这种念头我也有过,但很快就熄灭了,因为现实是残酷的,就算一开始的时间和精力非常充足,也会随着项目的推进而逐步消磨殆尽.我们会发现,自己越来越消极怠工,只是在无意义的敲代码,敲的还是网上抄来的代码,如果不行,继续找. 这就是项目进度没有规划好而导致的. 最近在做有关蓝牙的项目,一开始的进度都安排得很顺利,但是因为测试需要两部手机,而且还要是android手机,暑假已经开始了,同学们都回家了,加上我手机的蓝牙坏了,导致我的进度严重被打乱!而

【转】探讨android更新UI的几种方法----不错

原文网址:http://www.cnblogs.com/wenjiang/p/3180324.html 作为IT新手,总以为只要有时间,有精力,什么东西都能做出来.这种念头我也有过,但很快就熄灭了,因为现实是残酷的,就算一开始的时间和精力非常充足,也会随着项目的推进而逐步消磨殆尽.我们会发现,自己越来越消极怠工,只是在无意义的敲代码,敲的还是网上抄来的代码,如果不行,继续找. 这就是项目进度没有规划好而导致的. 最近在做有关蓝牙的项目,一开始的进度都安排得很顺利,但是因为测试需要两部手机,而且还