2014/03/07

Android 透過Handler更新UI


Layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView"
        android:layout_below="@+id/textView"
        android:layout_marginTop="34dp"
        android:text="Button" />

</RelativeLayout>







package com.cy.sample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
 TextView textView;
 Button button;
 MyThread myThread;
 static final int start = 0;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textView = (TextView) findViewById(R.id.textView);
  button = (Button) findViewById(R.id.buttonStart);
  button.setOnClickListener(clickListener);

 }

 final Button.OnClickListener clickListener = new OnClickListener() {

  @Override
  public void onClick(View v) {
   myThread = new MyThread();
   myThread.start();
  }
 };

 final Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case start:
    String str = "現在已經過了" + msg.arg1 + "秒";
    textView.setText(str);
    Log.i("time", str);
    break;
   }
  }
 };

 class MyThread extends Thread {
  @Override
  public void run() {
   int count = 0;

   while (!Thread.currentThread().isInterrupted()) {

    count++;

    Message message = new Message();
    message.what = start;
    message.arg1 = count;
    handler.sendMessage(message);

    try {
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }

  }
 }

}





參考資料:
http://rayleung.iteye.com/blog/411860
http://bbs.csdn.net/topics/360113917