標籤:android handler
劉昊昱
部落格:http://blog.csdn.net/liuhaoyutz
本文介紹了一個使用Handler的Android應用程式,通過該程式,我們可以瞭解Handler的基本用法。該程式運行效果如下:
點擊Button1按鈕後,運行效果如下:
點擊Button2按鈕後,運行效果如下:
下面我們來看這個程式碼。
主程式TestHandlerActivity.java內容如下:
package com.haoyu.testHandler;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class TestHandlerActivity extends Activity implements OnClickListener{TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button1 = (Button) findViewById(R.id.button1); Button button2 = (Button) findViewById(R.id.button2); textView = (TextView) findViewById(R.id.textView); button1.setOnClickListener(this); button2.setOnClickListener(this); } public Handler handler =new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what == 1)textView.setText("Button1 is clicked!");else if(msg.what == 2)textView.setText("Button2 is clicked!");elsetextView.setText("Unknown message!");} };@Overridepublic void onClick(View v) {// TODO Auto-generated method stubint id = v.getId();Message message = new Message();if(id == R.id.button1){ message.what = 1; handler.sendMessage(message);}if(id == R.id.button2){message.what = 2;handler.sendMessage(message);}}}
主布局檔案main.xml內容如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >" <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="60dp" android:textSize="20dp" android:gravity="center" android:id="@+id/textView" android:text="@string/prompt" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button1" android:id="@+id/button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button2" android:id="@+id/button2" /> </LinearLayout></LinearLayout>