按下工具栏上的后退按钮

时间:2016-10-03 09:14:32

标签: android android-actionbar

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

我试过但它不起作用。

在主要活动中添加。 onbackpress方法

@Override
public void onBackPressed() {
    super.onBackPressed();
    stopActivityTask();
}

3 个答案:

答案 0 :(得分:6)

你可以尝试这种方式..

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

答案 1 :(得分:1)

city.text = receivedString

答案 2 :(得分:1)

    private Toolbar toolbar;

然后在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);
}