Search code examples
androidbuttononclicklistener

Different Method to Set a Button's `OnClickListener` in Android


Is there a different way to set a button's OnClickListener besides the following method, such as through XML?

final Button button = (Button) findViewById(R.id.button_id);

button.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // Handle click event.
    }

});

Solution

  • 1) You have to implement OnClickListener in this option, and then implement its abstract method onClick(View).

    class YourClass implements OnClickListener {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.your_activity);
        final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(this);
       }
    
       public void onClick(View v) {
                //do something
       }
    }
    

    2) Another option, you can also specify the method that your Button will launch from your layout.xml file. You just have to do something like this:

    your_layout.xml

    <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="myCustomMethod" />
    

    And back to your acitivity class, you just implement that method

    class YourClass{ 
       ....
    
    
      public void myCustomMethod(View v){
        // do something
      }
    }