2014-11-04 31 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的帖子。