Android 工具栏点击 运行 所有任务

Android Toolbar clicks running all tasks

我有一个 Android 应用程序,它的工具栏上有几个图标。当我单击图标 R.id.barcode 时,它会执行 运行,但它还会调用 refreshList 方法,当单击另一个图标时,该方法设置为 运行工具栏。

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    switch (item.getItemId()) {
        case R.id.barcode:
            Intent i = new Intent(MainActivity.this, BarcodeScanner.class);
            startActivity(i);

        case R.id.refresh:
            refreshList();

    }
    return super.onOptionsItemSelected(item);
}

我找不到哪里出错了,因为像这样的其他结果]1 将其显示为案例陈述,但我不明白为什么它不能像这样工作预期的。

您需要在每个 case 语句中添加 break; 语句。

来自文档:

All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

参见示例 here