Four Android event handling methods

There are four ways to handle the event, such as the screen shot and the button

1. Use anonymous inner class processing

xml code

<Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Anonymous Inner Class "
        />

java code

btn1=(Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"Anonymous Inner Class ",Toast.LENGTH_SHORT).show();
            }
        });

2. Use inner class processing

xml code

<Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Inner class"
        />

java code

btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new MyOnClickListener());
public class MyOnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"Inner class",Toast.LENGTH_SHORT).show();
        }
    }

3. Use Activity itself as event listener class

xml code

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Activity"
        />

java code

MainActivity needs to be implemented View.OnClickListener

public class MainActivity extends AppCompatActivity implements View.OnClickListener{}

And implement the onClick method

@Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this,"Activity class",Toast.LENGTH_SHORT).show();
    }

onCreate method

btn3=(Button)findViewById(R.id.btn3);
btn3.setOnClickListener(this);

4. Binding to tags

xml code

Bind the required method on the onClick tag of xml, and write the method name for the attribute value

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="label"
        android:onClick="onclickListener"
        />

java code

The onclickListener method is added in MainActivity to correspond to the onClick attribute value in xml

public void onclickListener(View source){
        Toast.makeText(MainActivity.this,"label",Toast.LENGTH_SHORT).show();
    }

Tags: Android xml Java Attribute

Posted on Tue, 30 Jun 2020 12:21:15 -0400 by andrewburgess