在单击 ActionBar 的向上按钮时显示警报

Show an Alert on clicking Up button of ActionBar

我想在用户单击 ActionBar 的向上按钮时显示 Alert Dialog。我已经实现了 onBackPressed()。我现在想要做的是在用户单击 ActionBar 中的 Up 按钮时触发与按下 Back 按钮相同的操作。

我尝试使用 onNavigateUp()。但是,它只是 returns 我向父级 activity 显示警报对话框。

从这个answer你可以覆盖onOptionsItemSelected来检测动作

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home: {
       //enter your code here

        return true;
    }
}
return super.onOptionsItemSelected(item);
}

试一试