简体   繁体   中英

Jump to another activity when clicking a item in menu of actionbar in android studio

This is the code for select items in menu, when user click logout, the activity jumps to login_activity, when user clicks account, the activity jumps to account_activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout_id:
            Intent login = new Intent(MainpanelActivity.this, LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
        case R.id.account_id:
            Intent account =new Intent(MainpanelActivity.this,AccountActivity.class);
            startActivity(account);
            default:
                return super.onOptionsItemSelected(item);
    }
}

However, during the testing, no matter what i click, the activity always jumps to the account activity.

If i switch the order of the switch cases

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.account_id:
            Intent account =new Intent(MainpanelActivity.this,AccountActivity.class);
            startActivity(account);
        case R.id.logout_id:
            Intent login = new Intent(MainpanelActivity.this, LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);

            default:
                return super.onOptionsItemSelected(item);
    }
}

no matter what i click, the activity always jumps to the login_activity. Anybody knows why?

You need to add break; to in each case like below. Otherwise your code will execute the case that satisfies the switch condition and each case after it until either a break; or the end of the switch is reached.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.account_id:
            Intent account =new Intent(MainpanelActivity.this,AccountActivity.class);
            startActivity(account);
            break;
        case R.id.logout_id:
            Intent login = new Intent(MainpanelActivity.this, LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM