Android 按下工具栏上的“后退”按钮

Android 按下工具栏上的“后退”按钮,android,android-actionbar,Android,Android Actionbar,我如何为我的android应用程序创建一个代码,当我按下工具栏(操作栏)上的后退按钮时,一些代码将发生 我试过了,但没用 添加到主要活动中。反压法 @Override public void onBackPressed() { super.onBackPressed(); stopActivityTask(); } 然后将其添加到onCreate方法中 toolbar = (Toolbar) findViewById(R.id.toolbar); setSupp

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

我试过了,但没用

添加到主要活动中。反压法

@Override
public void onBackPressed() {
    super.onBackPressed();
    stopActivityTask();
}
然后将其添加到onCreate方法中

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
然后添加以下行:

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        /*
            ADD WHAT YOU WANT TO DO WHEN ARROW IS PRESSED
        */
        return super.onOptionsItemSelected(item);
}
你可以这样试试

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

检查我的答案:当用户按下后退按钮时,将调用onBackPressed()方法;如果我没说错的话,你的意思是“主页”按钮。谢谢。。第一个方法起作用。如果第一个方法不起作用,则加载项片段->设置选项菜单(true)
@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();
            }
        });