1. Are you ready for the Galaxy S20? Here is everything we know so far!

Methods to implement a button listener

Discussion in 'Android Development' started by robothito, Feb 13, 2016.

  1. robothito

    robothito Newbie
    Thread Starter

    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:
    Code (Java):
    1. public void addListenerOnButton(){
    3.         pass_word=(EditText)findViewById(R.id.editText3);
    4.         button_sbm=(Button) findViewById(R.id.button2);
    6.         button_sbm.setOnClickListener(new View.OnClickListener() {
    7.                                           @Override
    8.                                           public void onClick(View v) {
    9.                                               //Here we display the message with Toast
    10.                                               Toast.makeText(MainActivity.this,pass_word.getText(), Toast.LENGTH_SHORT).show();
    12.                                           }
    13.                                       }
    15.         );
    18.     }
    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

  2. Best Answer:
    Post #2 by Deleted User, Feb 13, 2016 (1 points)

    1. Download the Forums for Android™ app!


  3. Deleted User

    Deleted User Guest

    #2 Deleted User, Feb 13, 2016
    Last edited by a moderator: Feb 13, 2016
    robothito likes this.
  4. robothito

    robothito Newbie
    Thread Starter

    Excellent discussion . Thanks for point that to me! :)
    Deleted User likes this.

Share This Page