Liu Hao
Blog: Http://blog.csdn.net/liuhaoyutz
This article describes an Android application that uses handler, which allows us to understand the basic usage of handler. The program works as follows:
When you click the Button1 button, the effect is as follows:
When you click the Button2 button, the effect is as follows:
Let's look at this program code.
The main program Testhandleractivity.java content is as follows:
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);}}}
The main layout file Main.xml content is as follows:
<?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 "&G t; " <textview android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:paddingT op= "60DP" android:textsize= "20DP" android:gravity= "center" android:id= "@+id/textview" Android: text= "@string/prompt"/> <linearlayout android:layout_width= "Fill_parent" android:layou t_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" Andro Id:layout_height= "Wrap_cOntent "android:text=" @string/button2 "android:id=" @+id/button2 "/> </linearlayout></l Inearlayout>