单击工具栏的后退按钮时不会关闭活动

时间:2015-09-16 02:39:11

标签: android android-toolbar

参考下图, enter image description here
我想回到之前的活动 但是点击工具栏上的后退按钮,什么也没发生 我使用以下代码来实现仍然没有运气。

public boolean onOptionsItemSelected(MenuItem item){
       if(item.getItemId() == R.id.home)
       {
           finish();
       }
      return true;
    }

3 个答案:

答案 0 :(得分:14)

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                //NavUtils.navigateUpFromSameTask(this);
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

答案 1 :(得分:2)

在您的OnCreate方法

    toolbar.setTitle(R.string.title_activity_setting);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

在您的onOptionsItemSelected方法

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

我会工作。

答案 2 :(得分:0)

在您的活动中添加onBackPressed()方法。超级这个。当点击后退按钮时,请致电this.onBackPressed()。 更新此代码:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        this.onBackPressed();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

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