Android_handler (i)

Source: Internet
Author: User

Just a simple example of handler, the aim is to have a preliminary contact with handler.

Add a button to the layout, click on it, and print out the data transmitted using handler. (both are running in Mainthread)

1. Layout:

    <button        android:id= "@+id/buttonid"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:text=" @string/hello_world "/>
2. Activity:

Package Com.away.b_06_handler;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;public class Mainactivity extends Activity {private Button button;private Handler handler;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); button = (button) Findviewbyid (R.id.buttonid); Button.setonclicklistener (New Buttonlistener ()); handler = new Firsthandler ();} Class Buttonlistener implements Onclicklistener {@Overridepublic void OnClick (View v) {//When the user taps the button, we create a message object, and use handler to send the object message msg = Handler.obtainmessage (); (Obtainmessage gets the message object) Msg.what = 21;handler.sendmessage (msg);//The above line of code places the Message object in the message queue, and//1.Looper will be from the message queue, Remove the Message object.//2.Looper will find the handler object that corresponds to the Message object//3.Looper will call the handler object Handlermessage (Message msg) method for processing the messaging object}}class Firsthandler extends Handler {@Overridepublic void Handlemessage (Message msg) {int what = Msg.what; System.out.println ("What's:" + What);}}

Effect:


Android_handler (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.