Three ways to implement the listener in Android development (Onclicklistener)

Source: Internet
Author: User

There are three ways to implement the listener in Android development, and for beginners, a good understanding of these three methods will improve their understanding of the listener in Android.

First, what is the listener.

The listener is an interface that exists under the view class , and is typically named On******llistener, which requires the corresponding on**** (view V) method to be replicated (for example, onclick (view v)).

Ii. three ways to implement the listener

(Take Onclicklistener as an example)

Method One: Define an internal class inheritance listener interface in activity (this is Onclicklistener). The common inheritance methods are as follows:

class Implements view.onclicklistener{        @Override        publicvoid  OnClick (View v) {            Toast.maketext (mainactivity. This, "You have clicked Button2", Toast.length_short). Show ();        }    }

Alternatively, a new object of the Listener (Onclicklistener) can be used in a way that is similar to the direct inheritance above.

// or, here is the creation of a Onclicklistener object, which is similar to the direct replication interface above    Private New View.onclicklistener () {        @Override        publicvoid  OnClick (View v) {            Toast.maketext (mainactivity. This, "You have clicked Button2", Toast.length_short). Show ();        }    ;

The calls in the OnCreate () method are the same for the two implemented listeners above Bundle savedInstanceState , that is, the Setonclicklistener () method is used.

Bt2.setonclicklistener (new MyListener ());

Method Two: Implement an anonymous inner class. This approach is appropriate for situations where you want to use the listener only once, and after the block has finished running, the listener will no longer exist.

Bt1.setonclicklistener (new  View.onclicklistener () {            @Override            publicvoid  OnClick (View v) {                toast.maketext (mainactivity. This, "You have clicked Button1", Toast.length_short). Show ();            }        );

Method Three: Take advantage of the onclick attribute in the layout file and implement the method in the implementation file. Note that the method name here should be the same as the method name of the OnClick property in the layout file, which must be the public method.

// method Three, note that the public method    is required  Public void OnButtonClick (view view) {        Toast.maketext (mainactivity. This, "You have clicked Button3", Toast.length_short). Show ();    }}

Settings in the layout file

< Button         Android:layout_below = "@id/button2"         android:layout_width= "Wrap_content"        android:layout_height= "Wrap_ Content "        android:id=" @+id/button3 "        android:text=" Button3 "        android:onclick=" OnButtonClick "/>

These are the three ways to implement listeners in Android.

Here is the complete code for the entire project

Layout file:

<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.jeffrey.listener.MainActivity">    <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/text"Android:text= "Onclicklistener" />    <ButtonAndroid:layout_below= "@id/text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Button1"Android:id= "@+id/button1"/>    <ButtonAndroid:layout_below= "@id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Button2"Android:id= "@+id/button2"/>    <ButtonAndroid:layout_below= "@id/button2"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/button3"Android:text= "Button3"Android:onclick= "OnButtonClick"/></Relativelayout>

Implementation file:

 PackageCom.example.jeffrey.listener;ImportAndroid.content.DialogInterface;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Button BT1= (Button) Findviewbyid (R.id.button1);//corresponding method twoButton BT2 = (button) Findviewbyid (R.id.button2);//Correspondence Method OneBt1.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (mainactivity. This, "You have clicked Button1", Toast.length_short). Show ();        }        }); Bt2.setonclicklistener (NewMyListener ()); }    classMyListenerImplementsview.onclicklistener{@Override Public voidOnClick (View v) {toast.maketext (mainactivity. This, "You have clicked Button2", Toast.length_short). Show (); }    }    //or, here is the creation of a Onclicklistener object, which is similar to the direct replication interface above    PrivateView.onclicklistener MyListener =NewView.onclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (mainactivity. This, "You have clicked Button2", Toast.length_short). Show ();    }    }; //method Three, note that the public method is required     Public voidOnButtonClick (view view) {Toast.maketext (mainactivity. This, "You have clicked Button3", Toast.length_short). Show (); }}

Output: When clicked on the corresponding button, "Do you have clicked button?" appears. The prompt.

Summary: There are three ways to say that each has its advantages. The first approach is to start with beginners must learn. Compared with the first method, the two methods are more common in Android development and are often recommended by the gods. As far as I want to use that method, I look at my interest.

Three ways to implement the listener in Android development (Onclicklistener)

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.