没有xml的动画片段

时间:2014-11-04 07:20:24

标签: android xml animation android-fragments objectanimator

我正在寻找一种不使用xml来动画片段转换的方法。

设置片段动画的典型方法是将xml动画制作者与片段一起传递给FragmentTransaction.setCustomAnimations(例如,见https://stackoverflow.com/a/4936159/1290264

相反,我想发送setCustomAnimations ObjectAnimator以应用于片段,但遗憾的是,这不是一个选项。

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:2)

我找到了添加Animator的方法。

通过在将片段添加到fragmentManager之前覆盖片段的onCreateAnimator方法来实现。例如,要在转换期间滑入和滑出动画,您可以执行以下操作:

@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 forum的问题部分。