2014-11-04 63 views
3

我正在寻找一种方法来在不使用xml的情况下对片段的转换进行动画处理。Animate Fragment without xml

动画片段的典型方法是将与片段一起传递一个xml动画师FragmentTransaction.setCustomAnimations(作为一个例子见https://stackoverflow.com/a/4936159/1290264

相反,我想发送一个setCustomAnimationsObjectAnimator被施加到片段,但遗憾的是,这不是一个选项。

关于如何完成这一任何想法?

回答

1

我找到了一种方法来添加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的帖子。