6

我正在寻找一种在不使用 xml 的情况下为片段的过渡设置动画的方法。

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

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

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

4

1 回答 1

3

我找到了一种添加Animator.

它是通过在将片段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();
    }
}

PS这个答案是由于这个论坛的问题部分的帖子。

于 2014-11-04T14:38:58.390 回答