Android: How to add a click listener to a Button (action listener)

As another quick Android example, this Java source code shows how to add a “click listener” (on click/tap event) to an Android Button:

public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.my_layout_id);

         final Button button = (Button) findViewById(R.id.my_cool_button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // your handler code here
             }
         });
     }

}

Important things to know are:

  • You need to add a listener to the Button
  • The listener you need is called an OnClickListener (not an ActionListener or ButtonClickListener, etc.)
  • You add the listener with the setOnClickListener method, and
  • You need to implement the onClick method

If you needed to see how to add a listener to an Android Button, I hope this example code is helpful.