Katharina Katharina - 1 month ago 11
Android Question

Animate fragments content before closing it

I am displaying a

FrameLayout
with some components inside a
Fragment
. In
onCreateView(..)
I am animating the content of the
FrameLayout
and everything works fine. Now I want to animate the content before closing the
Fragment
.

In my current solution I am overriding
onBackPressed()
in the parent
Activity
and then I'm calling the method
onBackPressed()
inside my
Fragment
and animating the content there. The problem with this solution is, that I want to inflate the
Fragment
from various activities and then this is not really a nice solution... Does anybody know a better approach?

Thanks for your help!

Note:

I also tried to override
onCreateView()
and
onPause()
but the animation is not shown if I start it in those methods

and the following method does not fulfill my requirements either as it animates the whole fragment and I want to animate the content

getActivity().getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_up, R.anim.slide_out_down, R.anim.slide_in_down)

Answer

Maybe you can try to handle onBackPressed in your fragment like below:

    yourRootLayout.setFocusableInTouchMode(true);
    yourRootLayout.requestFocus();
    yourRootLayout.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                animateMyViews();
                return true;
            }
            return false;
        }
    });
Comments