1. 程式人生 > >Android 標題欄新增返回按鈕及響應

Android 標題欄新增返回按鈕及響應

在Activity的onCreate方法中新增如下程式碼:

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