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://stackoverflow.com/a/4936159/1290264)

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?

Community
  • 1
  • 1
bcorso
  • 45,608
  • 10
  • 63
  • 75

1 Answers1

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.

bcorso
  • 45,608
  • 10
  • 63
  • 75