AndroidがクールなCheckBox効果を実現

18405 ワード

まず実現効果図を貼ります。

gifの効果はちょっと速すぎるかもしれません。本物のマシンで運転するほうが効果的です。私たちの主な考え方は、属性アニメーションを利用して、選択状態とチェックを動的に描画することです。上の効果図を見て、みんなが矢も盾もたまらずやってみたいと思いますので、始めましょう。
カスタムViewの第一歩:カスタム属性。

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="SmoothCheckBox">
 <!--        -->
 <attr name="duration" format="integer"></attr>
 <!--      -->
 <attr name="strikeWidth" format="dimension|reference"></attr>
 <!--      -->
 <attr name="borderColor" format="color|reference"></attr>
 <!--         -->
 <attr name="trimColor" format="color|reference"></attr>
 <!--      -->
 <attr name="tickColor" format="color|reference"></attr>
 <!--      -->
 <attr name="tickWidth" format="dimension|reference"></attr>
 </declare-styleable>
</resources>
私たちはCheckBoxをSmooth CheckBoxと名付けて、いくつかなどの属性を定義しました。このステップは簡単です。みんなはもう慣れました。
次にオンメアスを見てみます。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
 if (widthMode == MeasureSpec.EXACTLY) {
  mWidth = widthSize;
 } else {
  mWidth = 40;
 }

 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
 if (heightMode == MeasureSpec.EXACTLY) {
  mHeight = heightSize;
 } else {
  mHeight = 40;
 }
 setMeasuredDimension(mWidth, mHeight);
 int size = Math.min(mWidth, mHeight);
 center = size / 2;
 mRadius = (int) ((size - mStrokeWidth) / 2 / 1.2f);
 startPoint.set(center * 14 / 30, center * 28 / 30);
 breakPoint.set(center * 26 / 30, center * 40 / 30);
 endPoint.set(center * 44 / 30, center * 20 / 30);

 downLength = (float) Math.sqrt(Math.pow(startPoint.x - breakPoint.x, 2f) + Math.pow(startPoint.y - breakPoint.y, 2f));
 upLength = (float) Math.sqrt(Math.pow(endPoint.x - breakPoint.x, 2f) + Math.pow(endPoint.y - breakPoint.y, 2f));
 totalLength = downLength + upLength;
}
最初はSmooth CheckBoxの幅、高さを測っていましたが、デフォルトの幅の高さは勝手に定義されています。もちろん自分で修正して、改善してもいいです。それから半径などを設定します。最後のstartPoint、breakPoint、endPointはそれぞれ選択時にチェックした3つの点に対応しています。ダウンリンクとは、startPointとbreakPointの距離であり、対応するアップリンクとは、breakPointとendPointの距離である。以下の図です

onDraw(Canvas canvas)を見る前に、二つのアニメを見に行きます。それぞれ選択状態のアニメと未選択状態のアニメです。

//           
private void checkedAnimation() {
 animatedValue = 0f;
 tickValue = 0f;
 //         
 mValueAnimator = ValueAnimator.ofFloat(0f, 1.2f, 1f).setDuration(2 * duration / 5);
 mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
 //      
 mTickValueAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(3 * duration / 5);
 mTickValueAnimator.setInterpolator(new LinearInterpolator());
 mTickValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  @Override
  public void onAnimationUpdate(ValueAnimator valueAnimator) {
 //         
   tickValue = (float) valueAnimator.getAnimatedValue();
   postInvalidate();
  }
 });
 mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  @Override
  public void onAnimationUpdate(ValueAnimator valueAnimator) {
 //         
   animatedValue = (float) valueAnimator.getAnimatedValue();
   postInvalidate();
  }
 });
 mValueAnimator.addListener(new AnimatorListenerAdapter() {
  @Override
  public void onAnimationEnd(Animator animation) {
 //                 
   mTickValueAnimator.start();
   Log.i(TAG," mTickValueAnimator.start();");
  }
 });
 mValueAnimator.start();
}

//           
private void uncheckedAnimation() {
 animatedValue = 0f;
 mValueAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(2 * duration / 5);
 mValueAnimator.setInterpolator(new AccelerateInterpolator());
 mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  @Override
  public void onAnimationUpdate(ValueAnimator valueAnimator) {
   animatedValue = (float) valueAnimator.getAnimatedValue();
   postInvalidate();
  }
 });
 mValueAnimator.start();
}
この二つのアニメーションはSmooth CheckBoxをクリックする時に呼び出します。同様に、アニメーション実行中に動画実行の進捗を得て、postInvalidateを呼び出します。Smooth CheckBoxをリメイクさせます。これを見終わったら最終的な大技onDrawです。

@Override
protected void onDraw(Canvas canvas) {
 super.onDraw(canvas);
 canvas.save();
 drawBorder(canvas);
 drawTrim(canvas);
 if (isChecked) {
  drawTick(canvas);
 }
 canvas.restore();
}

//    
private void drawTick(Canvas canvas) {
 //         
 float temp = tickValue * totalLength;
 Log.i(TAG, "temp:" + temp + "downlength :" + downLength);
 //              ,   startPoint
 if (Float.compare(tickValue, 0f) == 0) {
  Log.i(TAG, "startPoint : " + startPoint.x + ", " + startPoint.y);
  path.reset();
  path.moveTo(startPoint.x, startPoint.y);
 }
 //             breakPoint   , (breakPoint,endPoint]
 if (temp > downLength) {
  path.moveTo(startPoint.x, startPoint.y);
  path.lineTo(breakPoint.x, breakPoint.y);
  Log.i(TAG, "endPoint : " + endPoint.x + ", " + endPoint.y);
  path.lineTo((endPoint.x - breakPoint.x) * (temp - downLength) / upLength + breakPoint.x, (endPoint.y - breakPoint.y) * (temp - downLength) / upLength + breakPoint.y);
 } else {
 //        startPoinit breakPoint  , (startPoint,breakPoint]
  Log.i(TAG, "down x : " + (breakPoint.x - startPoint.x) * temp / downLength + ",down y: " + (breakPoint.y - startPoint.y) * temp / downLength);
  path.lineTo((breakPoint.x - startPoint.x) * temp / downLength + startPoint.x, (breakPoint.y - startPoint.y) * temp / downLength + startPoint.y);
 }
 canvas.drawPath(path, tickPaint);
}

//    
private void drawBorder(Canvas canvas) {
 float temp;
 //   animatedValue       “OverShooting”   
 if (animatedValue > 1f) {
  temp = animatedValue * mRadius;
 } else {
  temp = mRadius;
 }
 canvas.drawCircle(center, center, temp, borderPaint);
}

//  checkbox  
private void drawTrim(Canvas canvas) {
 canvas.drawCircle(center, center, (mRadius - mStrokeWidth) * animatedValue, trimPaint);
}
onDrawコードの論理には基本的に注釈が付けられています。原理がわかったら簡単です。チェックを描く時は、現在のチェックのどの状態にあるかを区別し、処理に応じて線を引くと、残りは簡単です。Smooth CheckBoxについての説明はここまでです。
以下はSmooth CheckBoxの完全なコードを貼り付けます。

public class SmoothCheckBox extends View implements View.OnClickListener {

 //       
 private long duration;
 //     
 private float mStrokeWidth;
 //     
 private float mTickWidth;
 //     
 private Paint trimPaint;
 //     
 private Paint borderPaint;
 //     
 private Paint tickPaint;
 //       
 private float defaultStrikeWidth;
 //       
 private float defaultTickWidth;
 //   
 private int mWidth;
 //   
 private int mHeight;
 //     
 private int borderColor;
 //     
 private int trimColor;
 //     
 private int tickColor;
 //   
 private int mRadius;
 //    
 private int center;
 //      
 private boolean isChecked;
 //       
 private float downLength;
 //       
 private float upLength;
 //       
 private float totalLength;
 //    
 private OnCheckedChangeListener listener;

 private ValueAnimator mValueAnimator;

 private ValueAnimator mTickValueAnimator;

 private float animatedValue;

 private float tickValue;
 //      
 private Point startPoint = new Point();
 //      
 private Point breakPoint = new Point();
 //      
 private Point endPoint = new Point();

 private static final String TAG = "SmoothCheckBox";

 private static final String KEY_INSTANCE_STATE = "InstanceState";

 private Path path = new Path();

 public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
  this.listener = listener;
 }

 public SmoothCheckBox(Context context) {
  this(context, null);
 }

 public SmoothCheckBox(Context context, AttributeSet attrs) {
  this(context, attrs, 0);
 }

 public SmoothCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SmoothCheckBox);
  duration = a.getInt(R.styleable.SmoothCheckBox_duration, 600);

  defaultStrikeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
  mStrokeWidth = a.getDimension(R.styleable.SmoothCheckBox_strikeWidth, defaultStrikeWidth);
  defaultTickWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
  mTickWidth = a.getDimension(R.styleable.SmoothCheckBox_tickWidth, defaultTickWidth);
  borderColor = a.getColor(R.styleable.SmoothCheckBox_borderColor, getResources().getColor(android.R.color.darker_gray));
  trimColor = a.getColor(R.styleable.SmoothCheckBox_trimColor, getResources().getColor(android.R.color.holo_green_light));
  tickColor = a.getColor(R.styleable.SmoothCheckBox_tickColor, getResources().getColor(android.R.color.white));
  a.recycle();

  trimPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  trimPaint.setStyle(Paint.Style.FILL);
  trimPaint.setColor(trimColor);

  borderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  borderPaint.setStrokeWidth(mStrokeWidth);
  borderPaint.setColor(borderColor);
  borderPaint.setStyle(Paint.Style.STROKE);

  tickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  tickPaint.setColor(tickColor);
  tickPaint.setStyle(Paint.Style.STROKE);
  tickPaint.setStrokeCap(Paint.Cap.ROUND);
  tickPaint.setStrokeWidth(mTickWidth);

  setOnClickListener(this);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  if (widthMode == MeasureSpec.EXACTLY) {
   mWidth = widthSize;
  } else {
   mWidth = 40;
  }

  int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  if (heightMode == MeasureSpec.EXACTLY) {
   mHeight = heightSize;
  } else {
   mHeight = 40;
  }
  setMeasuredDimension(mWidth, mHeight);
  int size = Math.min(mWidth, mHeight);
  center = size / 2;
  mRadius = (int) ((size - mStrokeWidth) / 2 / 1.2f);
  startPoint.set(center * 14 / 30, center * 28 / 30);
  breakPoint.set(center * 26 / 30, center * 40 / 30);
  endPoint.set(center * 44 / 30, center * 20 / 30);

  downLength = (float) Math.sqrt(Math.pow(startPoint.x - breakPoint.x, 2f) + Math.pow(startPoint.y - breakPoint.y, 2f));
  upLength = (float) Math.sqrt(Math.pow(endPoint.x - breakPoint.x, 2f) + Math.pow(endPoint.y - breakPoint.y, 2f));
  totalLength = downLength + upLength;
 }

 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  canvas.save();
  drawBorder(canvas);
  drawTrim(canvas);
  if (isChecked) {
   drawTick(canvas);
  }
  canvas.restore();
 }

 @Override
 protected Parcelable onSaveInstanceState() {
  Bundle bundle = new Bundle();
  bundle.putParcelable(KEY_INSTANCE_STATE, super.onSaveInstanceState());
  bundle.putBoolean(KEY_INSTANCE_STATE, isChecked);
  return bundle;
 }

 @Override
 protected void onRestoreInstanceState(Parcelable state) {
  if (state instanceof Bundle) {
   Bundle bundle = (Bundle) state;
   boolean isChecked = bundle.getBoolean(KEY_INSTANCE_STATE);
   setChecked(isChecked);
   super.onRestoreInstanceState(bundle.getParcelable(KEY_INSTANCE_STATE));
   return;
  }
  super.onRestoreInstanceState(state);
 }

 //     
 private void toggle() {
  isChecked = !isChecked;
  if (listener != null) {
   listener.onCheckedChanged(this, isChecked);
  }
  if (isChecked) {
   checkedAnimation();
  } else {
   uncheckedAnimation();
  }
 }

 //           
 private void checkedAnimation() {
  animatedValue = 0f;
  tickValue = 0f;
  mValueAnimator = ValueAnimator.ofFloat(0f, 1.2f, 1f).setDuration(2 * duration / 5);
  mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
  mTickValueAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(3 * duration / 5);
  mTickValueAnimator.setInterpolator(new LinearInterpolator());
  mTickValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    tickValue = (float) valueAnimator.getAnimatedValue();
    postInvalidate();
   }
  });
  mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    animatedValue = (float) valueAnimator.getAnimatedValue();
    postInvalidate();
   }
  });
  mValueAnimator.addListener(new AnimatorListenerAdapter() {
   @Override
   public void onAnimationEnd(Animator animation) {
    mTickValueAnimator.start();
    Log.i(TAG," mTickValueAnimator.start();");
   }
  });
  mValueAnimator.start();
 }

 //           
 private void uncheckedAnimation() {
  animatedValue = 0f;
  mValueAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(2 * duration / 5);
  mValueAnimator.setInterpolator(new AccelerateInterpolator());
  mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    animatedValue = (float) valueAnimator.getAnimatedValue();
    postInvalidate();
   }
  });
  mValueAnimator.start();
 }

 //    
 private void drawTick(Canvas canvas) {
  float temp = tickValue * totalLength;
  Log.i(TAG, "temp:" + temp + "downlength :" + downLength);
  if (Float.compare(tickValue, 0f) == 0) {
   Log.i(TAG, "startPoint : " + startPoint.x + ", " + startPoint.y);
   path.reset();
   path.moveTo(startPoint.x, startPoint.y);
  }
  if (temp > downLength) {
   path.moveTo(startPoint.x, startPoint.y);
   path.lineTo(breakPoint.x, breakPoint.y);
   Log.i(TAG, "endPoint : " + endPoint.x + ", " + endPoint.y);
   path.lineTo((endPoint.x - breakPoint.x) * (temp - downLength) / upLength + breakPoint.x, (endPoint.y - breakPoint.y) * (temp - downLength) / upLength + breakPoint.y);
  } else {
   Log.i(TAG, "down x : " + (breakPoint.x - startPoint.x) * temp / downLength + ",down y: " + (breakPoint.y - startPoint.y) * temp / downLength);
   path.lineTo((breakPoint.x - startPoint.x) * temp / downLength + startPoint.x, (breakPoint.y - startPoint.y) * temp / downLength + startPoint.y);
  }
  canvas.drawPath(path, tickPaint);
 }

 //    
 private void drawBorder(Canvas canvas) {
  float temp;
  if (animatedValue > 1f) {
   temp = animatedValue * mRadius;
  } else {
   temp = mRadius;
  }
  canvas.drawCircle(center, center, temp, borderPaint);
 }

 //  checkbox  
 private void drawTrim(Canvas canvas) {
  canvas.drawCircle(center, center, (mRadius - mStrokeWidth) * animatedValue, trimPaint);
 }

 @Override
 public void onClick(View view) {
  toggle();
 }

 /**
  *   checkbox      
  *
  * @return
  */
 public boolean isChecked() {
  return isChecked;
 }

 /**
  *   checkbox   
  *
  * @param isChecked     
  */
 public void setChecked(boolean isChecked) {
  this.setChecked(isChecked, false);
 }

 /**
  *   checkbox   
  *
  * @param isChecked     
  * @param isAnimation         
  */
 public void setChecked(boolean isChecked, boolean isAnimation) {
  this.isChecked = isChecked;
  if (isAnimation) {
   if (isChecked) {
    checkedAnimation();
   } else {
    uncheckedAnimation();
   }
  } else {
   animatedValue = isChecked ? 1f : 0f;
   tickValue = 1f;
   invalidate();
  }
  if (listener != null) {
   listener.onCheckedChanged(this, isChecked);
  }
 }

 public interface OnCheckedChangeListener {
  void onCheckedChanged(SmoothCheckBox smoothCheckBox, boolean isChecked);
 }
}
締め括りをつける
以上はこの文章の全部の内容です。本文の内容は皆さんの学習や仕事に一定の助けをもたらしてほしいです。もし疑問があれば、メッセージを残して交流してもいいです。