作者:刘昊昱
博客: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(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what == 1) textView.setText("Button1 is clicked!"); else if(msg.what == 2) textView.setText("Button2 is clicked!"); else textView.setText("Unknown message!"); } }; @Override public void onClick(View v) { // TODO Auto-generated method stub int 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>
Android架构分析之Handler分析(一),布布扣,bubuko.com
原文地址:http://blog.csdn.net/liuhaoyutz/article/details/25808659