2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Fragment内で端末の戻るボタンを押した際の制御を行う

Posted at

自分が作っているアプリで端末の戻るボタンを制御する必要があり、Android Developers の公式リファレンスに簡単に制御する方法が載っていたのでその備忘録。

実装

基本的にこちらに書かれているのですが、以下の手順を行ます。

  1. Fragment 内で activity から onBackPressedDispatcher のインスタンスを取得

  2. onBackPressedDispatcher#addCallbackLifecycleOwnerOnBackPressedCallback を渡す。

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // ここで戻るボタンがタップされた時の処理を行う。
            }
        })
    }

終わりに

AndroidX が出る前は端末の戻るボタンを制御する際は結構めんどくさかったのですが、今は Fragment からも操作できるようになっていてとても簡単だなと思いました。
相変わらず Android が進化していて開発していてとても楽しいです。☺️

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?