Three methods of event listening and three methods of event listening
1. Add three buttons to the activity_main.xml file.
<LinearLayout xmlns: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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn" /> <Button android:id="@+id/btn2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn" /> <Button android:id="@+id/btn3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn" /></LinearLayout>
2,
Method 1: Implement event listening through internal classes
/* Method 1: Implement event listening through internal Classes */btn1.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Log. I ("tag", "first method: Implement event listening through internal classes"); Toast. makeText (MainActivity. this, "the first button is clicked", Toast. LENGTH_SHORT ). show ();}});
3,
Method 2: Implement event listening through external classes (implement independently)
/* Method 2: Implement event listening through external classes (implemented independently) */btn2.setOnClickListener (new MyOnClickListener () {@ Override public void onClick (View v) {super. onClick (v); Log. I ("tag", "second method: Implement event listening through internal classes") ;}}); class MyOnClickListener implements View. onClickListener {@ Override public void onClick (View v) {Toast. makeText (MainActivity. this, "the second button is clicked", Toast. LENGTH_SHORT ). show ();}}
Note: The second method is to implement event listening through the external class (implemented independently). This method is generally used when multiple components need to implement the same method.
4,
Method 3: Implement event listening through the OnClickListener Interface
Public class MainActivity extends Activity implements View. onClickListener {private Button btn3; protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn3.setOnClickListener (this);}/* method 3: Implement event listening through the OnClickListener interface */@ Override public void onClick (View v) {Log. I ("tag", "method 3: event listening through the OnClickListener interface ");}}
Note: btn3.setOnClickListener (this); here, this Is The onClick method under OnClickListener.