Fragment animation without xml

I am looking for a way to make a fragment transition animation without using xml.

The typical way to animate a fragment is to pass the xml animator along with the fragment in FragmentTransaction.setCustomAnimations

(see stack overflow for an example )

Instead, I would like to send setCustomAnimations

a ObjectAnimator

to be applied to the fragment, but unfortunately this is not an option.

Any ideas on how this can be done?

+3


source to share


1 answer


I found a way to add Animator

.

This is accomplished by overriding the fragment method onCreateAnimator

before adding it to the fragment file. For example, to insert and disable animation during a 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();
    }
}

      

PS this answer is thanks to the topic section of this forum .

+1


source







All Articles