views:

3625

answers:

2

Let's say I have a few buttons in a LinearLayout, 2 of them are:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards)); exit_button = ((Button)this.findViewById(R.id.Button_Exit));

I register setOnClickListener() on both of them:

mycards_button.setOnClickListener(this); exit_button.setOnClickListener(this);

How do I make a SWITCH to differentiate between the two buttons within the Onclick ?

public void onClick(View v) {

switch(?????){ case ???: /** Start a new Activity MyCards.java */ Intent intent = new Intent(this, MyCards.class); this.startActivity(intent); break;

case ???:
 /** AlerDialog when click on Exit */
 MyAlertDialog();

break; }

+6  A: 

Try: public void onClick(View v) {

  switch(v.getId()){

  case R.id.Button_MyCards): /** Start a new Activity MyCards.java */
  Intent intent = new Intent(this, MyCards.class);
  this.startActivity(intent);
  break;

  case R.id.Button_Exit: /** AlerDialog when click on Exit */
  MyAlertDialog();
  break;
  }
AshtonBRSC
works just great ! I wonder how I haven't tried this by myself! Thanks a lot dude.H.
Hubert
+1  A: 

Another option is to add a new OnClickListener as parameter in setOnClickListener() and overriding the onClick()-method:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards)); 
exit_button = ((Button)this.findViewById(R.id.Button_Exit));

// Add onClickListener to mycards_button
mycards_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Start new activity
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
    }
});

// Add onClickListener to exit_button
exit_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Display alertDialog
        MyAlertDialog();
    }
});
aspartame
I have always found that do be really messy
Faisal Abid
I like it, but I guess it's pretty much a matter of personal preference.
aspartame