This question already has answers here:
When toolbar back button is pressed

(4 个回答)


4年前关闭。




如何为我的 android 应用程序创建代码,当我按下工具栏(操作栏)上的后退按钮时,会发生一些代码。

我试过了,但它不起作用。

在主要 Activity 中添加。反压法
@Override
public void onBackPressed() {
    super.onBackPressed();
    stopActivityTask();
}

最佳答案

你可以试试这个方法..

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // this takes the user 'back', as if they pressed the left-facing

      triangle icon on the main android toolbar.
        // if this doesn't work as desired, another possibility is to call

        stopActivityTask();  // finish() here.
        getActivity().onBackPressed();
        return true;
    default:
        return super.onOptionsItemSelected(item);
}
}

如果不工作
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        // Title and subtitle
        toolbar.setTitle(R.string.about_toolbar_title);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopActivityTask();
                finish();
            }
        });

10-08 02:57