Android 标题栏上加一个返回按钮

217 阅读1分钟

在Java页面onCreate方法中添加

Toolbar toolbar = (Toolbar) findViewById(R.id.habit_detail_toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);

ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

重写onOptionsItemSelected方法

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