안 드 로 이 드 는 ItemDecoration 을 사용 하여 RecyclerView 에 워 터 마크 를 추가 합 니 다.

머리말
아래 그림 과 같이 워 터 마크 효과 가 있 습 니 다.실현 과정 에서 최종 적 으로 ItemDecoration 을 사용 하여 이 루어 집 니 다.그 중에서 두 가지 절차 가 있 습 니 다.사용자 정의 Drawable 로 워 터 마크 그림 을 완성 하고 ItemDecoration 을 사용 하여 워 터 마크 를 배치 합 니 다.
Demo 는 WatermarkFragment 에서 효과 도 는 다음 과 같다.

1.사용자 정의 Drawable 완성 워 터 마크 그림

public class MyDrawable extends Drawable {
 Paint mPaint;

 public MyDrawable() {
  mPaint = new Paint();
  mPaint.setColor(Color.parseColor("#1A000000"));
  mPaint.setAntiAlias(true);
  mPaint.setTextAlign(Paint.Align.LEFT);//         
  mPaint.setTextSize(54);
 }

 @Override public void draw(@NonNull Canvas canvas) {
  Rect r = getBounds();

  //     
  canvas.save();
  canvas.rotate(-30, r.left, r.bottom);
  canvas.drawText("       ", r.left, r.bottom, mPaint);

  canvas.restore();
 }

 /*
                wrap_content        ,       。
 */ 

 //  30 ,      
 @Override public int getIntrinsicHeight() {
  return (int) (Math.sqrt(3) / 3 * getIntrinsicWidth() + 0.5F);

 }

 @Override public int getIntrinsicWidth() {
  return (int) (mPaint.measureText("DecorationDraw") + 0.5F);
 }

 //...      

}

여기 서 말하자면 이 Drawable 을 사용자 정의 하 는 것 은 비교적 간단 하지만 이 단 계 를 생각하면 훨씬 간단 하 다.처음에는 ItemDecoration 에서 직접 옆 구 조 를 그 리 려 고 했 지만 나중에 너무 복잡 하 게 시도 해 보 았 기 때문에 Drawable 을 사용 하여 독립 한 후에 훨씬 순 조 롭 게 되 었 다.
2.ItemDecoration 레이아웃 워 터 마크 사용

public class MyDecoration extends RecyclerView.ItemDecoration {
 private Drawable mDivider;
 private int mScrollY;

 public MyDecoration() {
  mDivider = new MyDrawable();
 }

 @Override public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
  //      
  // canvas.drawColor(Color.WHITE);

  /*
   *        bounds      ,  top
   */
  int top = UIUtil.dp(20) - mScrollY;

  //         ,       ,     count 
  int itemCount = parent.getAdapter().getItemCount();

  //     
  for (int i = 0; i < itemCount; ++i) {
   int left = i % 2 == 0 ? UIUtil.dp(20) : parent.getMeasuredWidth() -mDivider.getIntrinsicWidth() - UIUtil.dp(20);

   //  setBounds        
   mDivider.setBounds(left, top, parent.getMeasuredWidth(), top + mDivider.getIntrinsicHeight());
   mDivider.draw(canvas);

   if (i % 2 == 0) {
    top += UIUtil.dp(20) + mDivider.getIntrinsicHeight();
   } else {
    top += UIUtil.dp(140) + mDivider.getIntrinsicHeight();
   }
  }

 }

 /*
  mScrollY    recyclerView     ,      onScrollListener dy    , item              
 */ 
 public void setScrollY(int scrollY) {
  this.mScrollY = scrollY;
 }
}

RecyclerView 에서:

private int totallyY = 0;

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
 @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
  totallyY += dy;
  myDecoration.setScrollY(totallyY);
  }
});
결어
이렇게 쓰 면 느낌 이 간단 하 다.처음에 이 루어 졌 을 때 확실히 어 려 웠 다.RecyclerView 는 정말 좋 고 예술 적 인 컨트롤 을 썼 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기