Animate Fragment without xml
Asked Answered
R

1

6

I am looking for a way to do animate a fragment's transition without using xml.

The typical way to animate a fragment is to pass a xml animator along with the fragment to FragmentTransaction.setCustomAnimations (as an example see https://mcmap.net/q/99602/-animate-the-transition-between-fragments)

Instead, I'd like to send setCustomAnimations an ObjectAnimator to be applied to the fragment, but sadly this is not an option.

Any ideas on how this can be accomplished?

Rizo answered 4/11, 2014 at 7:20 Comment(0)
R
3

I found a way to add the Animator.

It is achieved by overriding the fragment's onCreateAnimator method before adding it to the fragmentManager. As an example, to slide the animation in and out during transition you can do this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tutorial);
    if (savedInstanceState == null) {
        Fragment fragment = new MyFragment(){
            @Override
            public Animator onCreateAnimator(int transit, boolean enter, int nextAnim)
            {
                Display display = getActivity().getWindowManager().getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);

                Animator animator = null;
                if(enter){
                   animator = 
                     ObjectAnimator.ofFloat(this, "translationX", (float) size.x, 0);
                } else {
                   animator = 
                     ObjectAnimator.ofFloat(this, "translationX", 0, (float) size.x);
                }

                animator.setDuration(500);
                return animator;
            }
        }

        getFragmentManager().beginTransaction()
                .add(R.id.container, fragment)
                .commit();
    }
}

P.S. this answer is thanks to a post in question section of this forum.

Rizo answered 4/11, 2014 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.