Ad

Android : Same OnClickListener On Many Buttons

I'm trying to set same OnClickListener on many buttons on one fragment.

So I tried to make the listener on top of the class such as

public class SigninUserInsurance extends Fragment {

       Button.OnClickListener thisListener = new Button.OnClickListener(){
             @Override
             public void onClick(View v){
                    .....
             }
       }

However, I want to save what the button's text is. (button.getText()).

But in the ... section,

since the thisListener does not have witch button it is, and it only gets the view,

I can't call the getText(). v.getText() doesn't exists.

For example, I tried my code in ... section as following,

 preferenceEditor.putString("User Insurance", Button.getText());
 preferenceEditor.commit();
 activity.fragChanger(4);

On the first line, Button.getText() can't be called because the thisListener does

not have the button information.

Is there any way without implementing every 10~ 20 button each own's listener??

Ad

Answer

You can define a listener object like this:

  View.OnClickListener thisListener = new View.OnClickListener() {
    public void onClick(View v) {
        Button button = (Button) v;
        switch (v.getId()) {
            case R.id.button1:
                 preferenceEditor.putString("User Insurance", button.getText());
                 preferenceEditor.commit();
                 activity.fragChanger(4); 
                 break;
            case R.id.button2:
                // 
                break;
            //...............
        } 
    }
  }

and set this listener to all of your buttons:

button1.setOnClickListener(thisListener);
button2.setOnClickListener(thisListener);
..........................................
Ad
source: stackoverflow.com
Ad