• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Methods to implement a button listener

robothito

Newbie
Feb 2, 2016
26
3
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:
Java:
public void addListenerOnButton(){

        pass_word=(EditText)findViewById(R.id.editText3);
        button_sbm=(Button) findViewById(R.id.button2);

        button_sbm.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          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
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones