Apps Methods to implement a button listener


Hello everybody and thanks for the help.

In order to make a button do some action I have learned two methods:

  1. Write a function (well, a class method ) and then click the onClick property of the button and select the method.
  2. Write a function (ok a class method) (a "listener") and inside this method define a Button button. Make this button recognize the button (with findViewById) and then set the setOnClickListener of the button with a new onClickListener. In other words this:
public void addListenerOnButton(){

        button_sbm=(Button) findViewById(;

        button_sbm.setOnClickListener(new View.OnClickListener() {
                                          public void onClick(View v) {
                                              //Here we display the message with Toast
                                              Toast.makeText(MainActivity.this,pass_word.getText(), Toast.LENGTH_SHORT).show();




The two methods do the same. Make the button do something.

Which of these methods is in your opinion preferable?? Pros and Cons??

Thanks a lot for your insights