Android_handler (1)

Source: Internet
Author: User

Android_handler (1)

It's just a simple example of handler. The purpose is to have a preliminary contact with handler.

Add a button on layout, click the button, and print the data transmitted using handler. (All are running on mainthread)

1. layout:

 

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 a user clicks the button, we create a Message object and use Handler to send the object Message msg = handler. obtainMessage (); // (obtainMessage obtains the message object) msg. what = 21; handler. sendMessage (msg); // The above line of code places the message object in the message queue, and then // 1. logoff will retrieve the message object from the message queue. // 2. logoff will find the Handler object corresponding to the message object // 3. logoff will call the handlerMessage (Message msg) method of the Handler object to process the Message object} class FirstHandler extends Handler {@ Overridepublic void handleMessage (Message msg) {int what = msg. what; System. out. println (What is: + what );}}}

Effect:

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.