user3011685 user3011685 - 5 months ago 15
Android Question

Multiple Buttons `OnClickListener()` android

I'm currently making a simple calculator app on Android. Im trying to set up the code so that when a number button is pressed it updates the calculator screen with that number. Currently I'm doing it like this.

Button one = (Button) findViewById(R.id.oneButton);
one.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView output = (TextView) findViewById(R.id.output);
output.append("1");
}
});


It works but I'm writing this same code for every single button on the calculator. As you can imagine it is very redundant. Is there anyway I can write this code in a more efficient way? One that involves not writing this method for every single button?

Answer

You Just Simply have to Follow these steps for making it easy...

You dont have to write new onClickListener for Every Button... Just Implement OnClickLister to your Activity/Fragment.. it will implement new Method called onClick() for handling onClick Events for Button,TextView` etc.

  1. Implement OnClickListener() in your Activity/Fragment
public class MainActivity extends Activity implements OnClickListener {

}
  1. Implement onClick() method in your Activity/Fragment
public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
      // default method for handling onClick Events..
    }

}
  1. Implement OnClickListener() For Buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(this); // calling onClick() method
    Button two = (Button) findViewById(R.id.twoButton);
    two.setOnClickListener(this);
    Button three = (Button) findViewById(R.id.threeButton);
    three.setOnClickListener(this);

}
  1. Find Buttons By Id and Implement Your Code..
@Override
public void onClick(View v) {

    switch (v.getId()) {

    case R.id.oneButton:
        // do your code
        break;

    case R.id.twoButton:
        // do your code
        break;

    case R.id.threeButton:
        // do your code
        break;

    default:
        break;
    }

}

This will make easier to handle many buttons click events and makes it looks simple to manage it...