RecyclerView.ItemDecoration 简单应用

demo
public class RollItemDecoration extends RecyclerView.ItemDecoration {

  private static final String TAG = "RollItemDecoration";

  private int index;
  private int topMin = 400;//小于等于展示图片的头部
  private int topMax = 800;//大于等于展示图片的尾部

  private Paint paint = new Paint();
  private Bitmap bitmap;
  private View bindView;

  /**
  * 画在Item下面
  *
  * @param c
  * @param parent
  * @param state
  */
  @Override
  public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
      super.onDraw(c, parent, state);

      if (bindView == null) {
          return;
      }

      final int left = parent.getPaddingLeft();
      final int right = parent.getWidth() - parent.getPaddingRight();

      final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) bindView
              .getLayoutParams();
      final int top = bindView.getBottom() + params.bottomMargin;
      //触发顶部重绘
      final int bottom = top + 300;
      RectF destRect = new RectF(left, top, right, bottom);

      //确定中间的滚动效果
      Rect srcRect;
      if (top < topMin) {
          srcRect = new Rect(0, 0, bitmap.getWidth(), 300);
      } else if (top > topMax) {
          srcRect = new Rect(0, bitmap.getHeight() - 300, bitmap.getWidth(), bitmap.getHeight());
      } else {
          //触发底部重绘
          int srcTop = bitmap.getHeight() * (top - 400) / (800 - 400);
          srcRect = new Rect(0, srcTop, bitmap.getWidth(), srcTop + 300);
      }

      c.drawBitmap(bitmap, srcRect, destRect, paint);
  }

  /**
  * 画在Item上面
  *
  * @param c
  * @param parent
  * @param state
  */
  @Override
  public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
      super.onDrawOver(c, parent, state);
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
      super.getItemOffsets(outRect, view, parent, state);

      if (parent.getChildAdapterPosition(view) == index) {
          this.bindView = view;
          outRect.set(0, 0, 0, 300);
      }
  }

  public void bindIndex(int index) {
      this.index = index;
  }

  public void bindImage(@Nullable Bitmap reFly) {
      this.bitmap = reFly;
  }
}

你可能感兴趣的:(RecyclerView.ItemDecoration 简单应用)