0

I have to show an animation when go back to previous fragment, so I must use a onBackPressed method. Since it's avaible just in activities, I tried to use a reference:

@Override
onBackPressed(){
super.onBackPressed();
infoFragment.onBackButtonPressed();
}

And in the InfoFragment I defined onBackButtonPressed method but it didn't work. So I tried like this:

view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if(i==KeyEvent.KEYCODE_BACK){
                    MainActivity mainActivity=(MainActivity)getActivity();
                    mainActivity.loadMainFragment();
                    return true;
                }
                return false;
            }
        });

So, why it didn't work?

Andrei Pascale
  • 232
  • 1
  • 3
  • 16

1 Answers1

0

If you would like to delay the back press event until your custom animation finishes, you should rewrite your code according to this snippet.

@Override
public void onBackPressed(){
    infoFragment.onBackButtonPressed(new Runnable(){
        @Override
        public void run(){
            super.onBackPressed();
        }
    });
}

What's that runnable?

Your onBackButtonPressed method should get a runnable object and run it once the custom animation is over. This runnable is used as a callback function.

Using this way, you're delaying call to super.onBackPressed(), so you can first play your animation, then relaying the event to your activity's super class.

When should I call this runnable?

For your custom animation, attach an animation listener and call that runnable in onAnimationEnd method of it.

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129