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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With