2017-03-08 137 views
1

我有以下代碼來動畫RecyclerView項目。這項工作非常好,但它可以動畫顯示如果向下滾動顯示的所有項目。RecyclerView項目動畫:只動畫最初可見的項目

我想要的是一種類似於Google Play音樂應用中的行爲,其中動畫僅用於最初可見的項目。通過滾動顯示的項目應該顯示爲沒有動畫適配器。任何想法如何存檔這種行爲?

public class RecyclerViewAnimationAdapter : RecyclerView.Adapter 
    { 
     private int m_LastPosition = -1; 

     public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) 
     { 
      base.OnBindViewHolder(holder, position); 

      animateItem(position, holder.ItemView); 
     } 

     public override void OnViewDetachedFromWindow(Object holder) 
     { 
      base.OnViewDetachedFromWindow(holder); 

      var viewToAnimate = ((RecyclerView.ViewHolder) holder).ItemView; 

      viewToAnimate.ClearAnimation(); 
     } 

     private void animateItem(int position, View viewToAnimate) 
     { 
      if (position > m_LastPosition) 
      { 
       var animation = AnimationUtils.LoadAnimation(Application.Context, Resource.Animation.slide_in_bottom); 

       viewToAnimate.StartAnimation(animation); 

       m_LastPosition = position; 
      } 
     } 
    } 

回答

1

我測試了Android Studio中這種方法和它的工作,它應該爲您提供了一些小的調整工作太:

class YourAdapter extends RecyclerView.Adapter{ 
    private int lastPosition = -1; 
    private boolean isAnimation; 

    YourAdapter(...) 
    { 
     ... 
     this.isAnimation = true; 
    } 
    .... 


    private void switchAnimation(boolean isAnimation) 
    { 
     this.isAnimation = isAnimation; 
    } 


    private void animateItem(int position, View viewToAnimate) 
    { 
     if (position > m_LastPosition && isAnimation) 
     { 
      var animation = AnimationUtils.LoadAnimation(Application.Context, Resource.Animation.slide_in_bottom); 

      viewToAnimate.StartAnimation(animation); 

      m_LastPosition = position; 
     } 
    } 

}

然後在你的佈局管理覆蓋的方法onLayoutChildren(你必須容納代碼到C#):

layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false){ 
     @Override 
     public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 
      super.onLayoutChildren(recycler, state); 
      myAdapter.switchAnimation(false); 
     } 
    }; 

讓我知道這是否有幫助;)

+0

嗨納比爾。非常感謝。我會在今天晚些時候嘗試:) –

+0

謝謝。非常好! –