My Blog

~岩手から発信中~

【Android】ActionbarのボタンでHomeに戻る

Actionbarにあるボタンを押すことでホームに戻る処理を書いていきたいと思います。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.main, menu);

    switch (item.getItemId()){ // if使うとエラー(itemがInt形式なため)
    case android.R.id.home:   // アプリアイコン(ホームアイコン)を押した時の処理
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        break;
    }
    return true;
}

これでボタンを押すことでHomeに戻ることができます。


参考サイト:http://furudate.hatenablog.com/entry/2013/06/01/062205