Three methods for adding actions to android listening events

Source: Internet
Author: User

The first method is the method of getting started. It is usually defined directly in the oncreate event of the activity component and acts directly. In this way, each control is defined once, which is usually inconvenient.
Button btn = (Button) findViewById (R. id. myButton );
 
Btn. setOnClickListener (new View. OnClickListener (){
 
Public void onClick (View v ){
 
// Do something
 
}
 
});
The second method is usually to implement its interface in the activity component, so that multiple external controls can share an interface, which is relatively convenient
Public class TestMedia extends Activity implements View. OnClickListener {
 
Button btn1 = (Button) findViewById (R. id. myButton1 );
Button btn2 = (Button) findViewById (R. id. myButton2 );
 
Btn1. setOnClickListener ();
Btn2. setOnClickListener ();
 
}
 
Public void onClick (View v ){
 
Switch (v. getId ()){
 
Case R. id. myButton1:
 
// Do something
 
Break;
 
Case R. id. myButton2:
 
// Do something
 
Break;
 
}
 
The third method is similar to the second method. The advantage is that if you need to implement multiple listening interfaces, it is clearer.
 
Public class TestMedia extends Activity {
 
Button btn1 = (Button) findViewById (R. id. myButton1 );
Button btn2 = (Button) findViewById (R. id. myButton2 );
 
Btn1. setOnClickListener (new ClickEvent ());
 
Btn2. setOnClickListener (new ClickEvent ());
 
}
Class ClickEvent implements View. OnClickListener
 
Public void onClick (View v ){
 
Switch (v. getId ()){
 
Case R. id. myButton1:
 
// Do something
 
Break;
 
Case R. id. myButton2:
 
// Do something
 
Break;
 
}


From wyyew's blog

Related Article

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.