0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AndroidStudio アクションバー 戻る

Posted at

アクションバーに戻るボタンを配置

アクションバーが出ない時

この ← アイコン
image.png

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main2);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //戻るボタンを配置++++++++
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        //++++++++++++++++
    }
    //戻るボタンを押した時++++++++
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
            return true;
        }else{
            return super.onOptionsItemSelected(item);
        }
    }
    //++++++++++++++++
}

解説

  • ActionBar actionBar = getSupportActionBar();
    アクションバーオブジェクトの取得

  • actionBar.setDisplayHomeAsUpEnabled(true);
    戻るボタンを有効にする


//戻るボタンを押した時の処理
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  if(item.getItemId() == android.R.id.home){
    finish();
    return true;
  }else{
    eturn super.onOptionsItemSelected(item);
  }
}

  • android.R.id.home
    戻るボタンのid処理のfinish()で現在のページを消し、戻る
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?