[android] Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

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;
}

This question is related to android button listener

The answer is


I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_menu);

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

For my example :first 'MainActivity' implements 'View.OnClickListener' than start the code ....

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();}


public void init(){

    foryou = (Button) this.findViewById(R.id.btn_foryou);
    following = (Button) findViewById(R.id.btn_following);
    popular = (Button) findViewById(R.id.btn_popular);
    watching = (Button) findViewById(R.id.btn_continuewatching);
    mProgress = (ProgressBar) findViewById(R.id.pb);

    foryou.setOnClickListener(this);
    following.setOnClickListener(this);
    popular.setOnClickListener(this);
    watching.setOnClickListener(this);
    mProgress.setOnClickListener(this);
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_foryou:
            foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_following:
            following.setPaintFlags(following.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_popular:
            popular.setPaintFlags(popular.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_continuewatching:
            watching.setPaintFlags(watching.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_5:
            // foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        default:
            foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

    }
}

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();
    }
});

And there's yet a third option. In your onCreate() method, find all the button views that you have and save them as class data members. You can then cascade a group of if-else statements to find which is which. It's kind of messy, but it's a must if you don't know the ID of the buttons (which can be complicated if you are generating buttons in java code).

@Override
public void onClick(View v) {
    if (v == m_myCards) {
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
    }
    else if (v == m_exit) {
        MyAlertDialog();
    }
    else if (v == m_back) {
        finish();            
    }

Another nice thing about this technique is that it's flexible and quick (no having to parse IDs). The bad thing is that you need to keep the widgets in memory.

Don't know which method is better.


inside OnCreate method :-

{

    Button b = (Button)findViewById(R.id.button1);
    b.setOnClickListener((View.OnClickListener)this);

    b = (Button)findViewById(R.id.button2);
    b.setOnClickListener((View.OnClickListener)this);
} 

@Override
public void OnClick(View v){

    switch(v.getId()){
         case R.id.button1:
             //whatever
             break;

         case R.id.button2:
             //whatever
             break;
}

public class MainActivity extends Activity
        implements View.OnClickListener {
    private Button btnForward, btnBackword, btnPause, btnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initControl();
    }

    private void initControl() {
        btnForward = (Button) findViewById(R.id.btnForward);
        btnBackword = (Button) findViewById(R.id.btnBackword);
        btnPause = (Button) findViewById(R.id.btnPause);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnForward.setOnClickListener(this);
        btnBackword.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnForward:
                break;
            case R.id.btnBackword:
                break;
            case R.id.btnPause:
                break;
            case R.id.btnPlay:
                break;
        }
    }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to listener

Android - How to achieve setOnClickListener in Kotlin? Oracle client ORA-12541: TNS:no listener How to properly stop the Thread in Java? Can I have onScrollListener for a ScrollView? Create a custom event in Java TNS-12505: TNS:listener does not currently know of SID given in connect descriptor Remove an onclick listener Using Switch Statement to Handle Button Clicks JavaScript: remove event listener Counting Chars in EditText Changed Listener