Lemich Pablo February 2016

Add one click listener to two buttons, but perform different action

Well this is my code, for only one button, i want to have 2 buttons namely btnCalcu can someone help me? thank you all very much

Button btnSubmit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    btnSubmit = (Button) findViewById(R.id.button1);
    btnSubmit.setOnClickListener(this);
} 


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(this, Home1.class);

        startActivity(intent);


}

}

Answers


George Mulligan February 2016

You can use the same listener for both buttons and use an if statement on the id of the clicked View to know which one the user clicked like below:

@Override
public void onClick(View v) {
    if(v.getId() == R.id.button1) {
        // id matches submit button's id so btnSubmit clicked.
        Intent intent = new Intent(this, Home1.class);
        startActivity(intent);
    } else if(v.getId() == R.id.button2) {
        // id matches calculate button's id so btnCalcu clicked. 
        Intent intent = new Intent(this, OtherForm.class);
        startActivity(intent);
    }
}

In your onCreate method get your second button and set it up the same way as you did btnSubmit:

btnCalcu = (Button) findViewById(R.id.button2);
btnCalcu.setOnClickListener(this);

Post Status

Asked in February 2016
Viewed 2,884 times
Voted 8
Answered 1 times

Search




Leave an answer