工具栏返回按钮点击时活动未关闭

6

请参考下方图片, enter image description here
我想返回到之前的活动页面。
但是,当我在工具栏上点击返回按钮时,什么也没有发生。
我已经尝试使用以下代码来实现这一目标,但仍然没有成功。

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

16
@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
请将其翻译为中文:android.R.id.home - Aditya Naique
1
你需要使用 getSupportActionBar().setHomeButtonEnabled(true); 和 getSupportActionBar().setDisplayHomeAsUpEnabled(true);。 - QuinnChen

3
在您的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);
}

我会工作。


0
在您的Activity中添加onBackPressed()方法。并且调用super。当点击返回按钮时,调用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();
}

请记住以下代码:getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); - Phan Sinh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接