1. 程式人生 > >Handler更新UI的三種方式

Handler更新UI的三種方式

public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);

    /**
     * new Thread()在該執行緒中實現你具體的業務邏輯,比如網路請求,耗時操作等等;
     * new Thread()是一個子執行緒,是非UI執行緒,如果在該執行緒中需要更新介面,則需要使用Handler;
     *
     */
    new Thread() {
        @Override
        public void run() {//在run()方法實現業務邏輯;
            //...

            //更新UI操作;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    text.setText(使用Handler更新了介面);
                }
            });

        }
    }.start();
}}

 

public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);
    final MyRunnable myRunnable = new MyRunnable();//定義MyRunnable的物件;

    new Thread() {

        @Override
        public void run() {
            handler.post(myRunnable);//呼叫Handler.post方法;
        }
    }.start();
}

class MyRunnable implements Runnable {//內部類實現Runnable介面;

    @Override
    public void run() {//還是在Runnable重寫的run()方法中更新介面;
        text.setText(使用Handler更新了介面);
    }
}}
public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                text.setText(使用Handler更新了介面);
                break;
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);

    new Thread() {

        @Override
        public void run() {
            //...你的業務邏輯;
            Message message = new Message();//傳送一個訊息,該訊息用於在handleMessage中區分是誰發過來的訊息;
            message.what = 1;
            handler.sendMessage(message);
        }
    }.start();
}}