Fragment pressing back button

后端 未结 16 2348
清歌不尽
清歌不尽 2020-11-29 20:18

I am now having an activity containing fragments

[1] , [2] , [3] , [4]

If pressing buttons , [3] , it can be redirected to [4]

I would like to imp

16条回答
  •  無奈伤痛
    2020-11-29 21:12

    Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.

    One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.

    @Override
    public boolean onBackPressed() {
       if(some_condition)
          // Do something
          return true; //Back press consumed.
       } else {
          // Back-press not consumed. Let Activity handle it
          return false;
       }
    }
    

    Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this

    @Override
    public void onBackPressed() {
       if(!activeFragment.onBackPressed())
          super.onBackPressed();
       }
    }
    

    This post has this pattern described in detail

提交回复
热议问题