-2

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

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
mantc_sdr
  • 451
  • 3
  • 17
  • Possible duplicate of [How to implement onBackPressed() in Fragments?](https://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments) – ADM Feb 08 '19 at 11:29
  • @ADM I already read it before and is not answering my question – mantc_sdr Feb 08 '19 at 11:33

1 Answers1

1

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

Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
  • But I need to execute some code from Fragment A, and I guess your code is meant to be inserted in the Activity, right? – mantc_sdr Feb 08 '19 at 11:55
  • 1
    @mantc_sdr the code in my activity would create a dialog prompt to save changes or cancel and leave the fragment. If the user selects to save the dialog has an in built listener that saves everything before exiting. – Nikos Hidalgo Feb 08 '19 at 12:00
  • a listener implemented in the Fragment I guess, right? – mantc_sdr Feb 08 '19 at 12:06
  • 1
    @mantc_sdr the listener was just to check which dialog button the user clicks. If they wanted to save the changes, I just called a public method defined in the fragment as mCurrentFragment.save(); – Nikos Hidalgo Feb 08 '19 at 12:10