LoginSignup
1
3

More than 5 years have passed since last update.

フラグメントをネストしている場合に子フラグメント内での画面遷移をバックキーで戻したい場合

Last updated at Posted at 2018-09-20

Fragment内にFragmentを入れ子にしている場合(※1)に、子Fragmentでは、addToBackStack()メソッドを呼んでも、ハードキーのバックキーで一つ前に戻ることができない。その場合は、以下のコードを追加することで一つ前に戻ることができる。
(※1)getChildFragmentManager()を使用している場合

MainActivity.java
    @Override
    public void onBackPressed() {
        // if there is a fragment and the back stack of this fragment is not empty,
        // then emulate 'onBackPressed' behaviour, because in default, it is not working
        FragmentManager fm = getSupportFragmentManager();
        for (Fragment frag : fm.getFragments()) {
            if (frag.isVisible()) {
                FragmentManager childFm = frag.getChildFragmentManager();
                if (childFm.getBackStackEntryCount() > 0) {
                    childFm.popBackStack();
                    return;
                }
            }
        }
        super.onBackPressed();
    }
1
3
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
1
3