Search code examples
androidandroid-fragmentsonbackpressed

Managing fragment code from activity when back pressed


I have an Activity whose layout is a fragment which can be filled by different Fragments classes. The thing is that when I am in Fragment X and I press back, I would like to override onBackPressed method in order to execute a method asking the user whether to save input data. However, the problem is that onBackPressed can only be overwritten from the activity, then my question is:

Should I create a public method in Fragment X and call it from the overwritten onBackPressed method or should I use interfaces or whatever else?

I already checked other related posts like how to move back to the previous fragment without loosing data with addToBackStack, but I think this is a different question..


Solution

  • When I wanted to do something similar, I created tags for the fragments and a Fragment object in the parent activity named mCurrentFragment. Every time I would load a fragment, I assigned it to mCurrentFragment. So I would override the onbackPressed() from my activity and then check the fragment instances:

    @Override
    public void onBackPressed() {
        if (mCurrentFragment instanceof FragmentA) {
            //Do something
            //e.g. mCurrentFragment.save();
        } else if (mCurrentFragment instanceof FragmentB) {
            //Do something else
        } else {
            super.onBackPressed()
        }
    }
    

    If you want to call a method from a fragment, you just use the Fragment object you created (in my case mCurrentFragment) and get access to all of its public methods (as in the example for FragmentA above)

    §EDITED to include code from the comments