1

I have an activity with a fragment. I'm trying to execute some code when the user presses the back button. I'm trying to do so with this method in the activitiy's class:

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

and then I override it in my fragment with this code:

@Override
public void onBackPressed() {
    ((MyActivity)getActivity()).onBackPressed();
    doStuff();
}

What I'm trying to do here is to have the onBackPressed method overriden in the fragment's class and then have that method first call the method in its activity as I can't call getActivity().super.onBackPressed() from the fragment's onBackPressed() method. I've tried this and it doesn't work. In the activity's class it overrides the method just fine, but in the fragment's class the compiler complains that the fragment's onBackPressed() method doesn't override the method in it's super class. So, my question is, how can I do so correctly? Is that even possible?

Another way I could solve my problem is to have the full onBackPressed() method in my activity and have that one call a method of my fragment, but I can't do that as my fragment doesn't have an id (it is generated by the FragmentPagerAdapter).

user3154699
  • 67
  • 3
  • 11
  • read this http://stackoverflow.com/a/7016483/5202007 – Mohammad Tauqir Sep 22 '15 at 15:17
  • I've read most of the answers, but to my knowledge, none give the solution that I require. I'm starting to think that what I'm trying to do is impossible. I should also add that when the back button is pressed, my program doesn't destroy the current fragment and transition to another one. My fragment has a class that displays image elements, and when the back button is pressed it replaces those elements with new ones (all that in the same fragment). What I'm thinking I'll do is give my fragment a tag or an id, and then call a method in my fragment which will do the work from my activity. – user3154699 Sep 22 '15 at 16:00

1 Answers1

0

The solution turned out to be simple. In the activity class, I created a reference fragment. Then I passed that fragment to the FragmentPagerAdapter. Back in the onBackPress method I simply called fragmentreference.methodinfragment().

user3154699
  • 67
  • 3
  • 11