工作(我)太(太)忙(懒) 太长时间没有写博客了,再不写今年一晃就要过去了,顺便也总结下今年工作的一些技术点吧。这篇先从一个简单的自定义控件开始吧 先看最终效果图:
这是一个性别选择的控件 本质上是一个Switch类似的控件 需要满足的需求点有:
- 支持左右滑动选中
- 支持左右点击选中
- 支持按钮渐变色
- 支持选中和未选中状态字体颜色的变化
由此得出所涉及的自定义View的技术点有:
- View的触摸事件和滑动事件的处理
- 颜色渐变的计算相关api的运用
接下就从最基本的代码开始:
//初始化
public class GenderSwitchView extends View {
public GenderSwitchView(Context context) {
this(context, null);
}
public GenderSwitchView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public GenderSwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
}
初始逻辑
private ShapeDrawable backgroundDrawable;
private ShapeDrawable genderDrawable;
private float mProgress;
private int mTouchSlop;
private void initView(Context context) {
int testSize = SizeUtils.sp2px(16);
//这里是将宽高根据ui 设计图计算写死
height = SizeUtils.dp2px(45);
width = SizeUtils.dp2px(200);
//圆角角度
int radiis = SizeUtils.dp2px(80);
//获取系统识别最小的滑动距离
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
//获取系统触发点击事件的时长
mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();
selectTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
selectTextPaint.setTextAlign(Paint.Align.CENTER);
selectTextPaint.setTextSize(testSize);
selectTextPaint.setColor(Color.WHITE);
defaultTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
defaultTextPaint.setTextAlign(Paint.Align.CENTER);
defaultTextPaint.setTextSize(testSize);
defaultTextPaint.setColor(grayText);
mProgressAnimator = new ValueAnimator();
float[] outerRadii = {radiis, radiis, radiis, radiis, radiis, radiis, radiis, radiis};//外矩形 左上、右上、右下、左下的圆角半径
RectF inset = new RectF(0, 0, 0, 0);//内矩形距外矩形,左上角x,y距离, 右下角x,y距离
float[] innerRadii = {0, 0, 0, 0, 0, 0, 0, 0};//内矩形 圆角半径
RoundRectShape roundRectShape = new RoundRectShape(outerRadii, inset, innerRadii);
backgroundDrawable = new ShapeDrawable(roundRectShape);
int back_color = ContextCompat.getColor(context, R.color.col_f3f3f3);
backgroundDrawable.getPaint().setColor(back_color);
backgroundDrawable.setBounds(0, 0, width, height);
girlStartColor = ContextCompat.getColor(context, R.color.col_ff719e);
girlEndColor = ContextCompat.getColor(context, R.color.col_ffae9b);
boyStartColor = ContextCompat.getColor(context, R.color.col_55a8ff);
boyEndColor = ContextCompat.getColor(context, R.color.col_8998ff);
//渐变色计算类
argbEvaluator = new ArgbEvaluator();
RoundRectShape shape = new RoundRectShape(outerRadii, inset, innerRadii);
linearGradient = new LinearGradient(0, 0, boundsWidth, height, girlStartColor, girlEndColor, Shader.TileMode.REPEAT);
genderDrawable = new ShapeDrawable(shape);
genderDrawable.getPaint().setShader(linearGradient);
genderDrawable.getPaint().setStyle(Paint.Style.FILL);
boundsWidth = width / 2;
bundsX = (int) (mProgress * boundsWidth);
bounds = new Rect(bundsX, 0, boundsWidth + bundsX, height);
genderDrawable.setBounds(bounds);
}
其中这段代码创建的是最底层圆角矩形Drawable:
float[] outerRadii = {radiis, radiis, radiis, radiis, radiis, radiis, radiis, radiis};//外矩形 左上、右上、右下、左下的圆角半径
RectF inset = new RectF(0, 0, 0, 0);//内矩形距外矩形,左上角x,y距离, 右下角x,y距离
float[] innerRadii = {0, 0, 0, 0, 0, 0, 0, 0};//内矩形 圆角半径
RoundRectShape roundRectShape = new RoundRectShape(outerRadii, inset, innerRadii);
backgroundDrawable = new ShapeDrawable(roundRectShape);
int back_color = ContextCompat.getColor(context, R.color.col_f3f3f3);
backgroundDrawab
le.getPaint().setColor(back_color);
backgroundDrawable.setBounds(0, 0, width, height);
创建用于滑动的选择性别的Drawable,这个Drawable涉及渐变色 用到了LinearGradient
相关api Android之Shader用法详细介绍
//女士Drawable 颜色范围
girlStartColor = ContextCompat.getColor(context, R.color.col_ff719e);
girlEndColor = ContextCompat.getColor(context, R.color.col_ffae9b);
//男士Drawable 颜色范围
boyStartColor = ContextCompat.getColor(context, R.color.col_55a8ff);
boyEndColor = ContextCompat.getColor(context, R.color.col_8998ff);
RoundRectShape shape = new RoundRectShape(outerRadii, inset, innerRadii);
//颜色渐变
linearGradient = new LinearGradient(0, 0, boundsWidth, height, girlStartColor, girlEndColor, Shader.TileMode.REPEAT);
genderDrawable = new ShapeDrawable(shape);
//设置颜色渐变
genderDrawable.getPaint().setShader(linearGradient);
genderDrawable.getPaint().setStyle(Paint.Style.FILL);
//Drawable 宽高 为背景的一半
boundsWidth = width / 2;
bundsX = (int) (mProgress * boundsWidth);
bounds = new Rect(bundsX, 0, boundsWidth + bundsX, height);
genderDrawable.setBounds(bounds);
然后调用onDraw
进行绘制 看看效果:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//这里因为是知道具体宽高 在初始化的时候已经计算出来 这里直接设置进去即可
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
backgroundDrawable.draw(canvas);//先绘制背景Drawable
genderDrawable.draw(canvas);//再绘制上面一层用于可滑动的Drawable
}
效果:
到这里最基本的已经做完了 但是目前还不能滑动 所以要开始重写onTouchEvent
进行处理 这个也是这个自定义View 的重点 另外在滑动过程中择性别的Drawable需要渐变颜色:
float mStartX;
float mStartY;
float mLastX;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float deltaX = event.getX() - mStartX;
float deltaY = event.getY() - mStartY;
switch (action) {
case MotionEvent.ACTION_DOWN:
mStartX = event.getX();
mStartY = event.getY();
mLastX = mStartX;
setPressed(true);
break;
case MotionEvent.ACTION_MOVE:
float x = event.getX();
//计算滑动的比例 boundsWidth为整个宽度的一半
setProcess(getProgress() + (x - mLastX) / boundsWidth);
//这里比较x轴方向的滑动 和y轴方向的滑动 如果y轴大于x轴方向的滑动 事件就不在往下传递
if ((Math.abs(deltaX) > mTouchSlop / 2 || Math.abs(deltaY) > mTouchSlop / 2)) {
if (Math.abs(deltaY) > Math.abs(deltaX)) {
return false;
}
}
mLastX = x;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
setPressed(false);
//计算从手指触摸到手指抬起时的时间
float time = event.getEventTime() - event.getDownTime();
//如果x轴和y轴滑动距离小于系统所能识别的最小距离 切从手指按下到抬起时间 小于系统默认的点击事件触发的时间 整个行为将被视为触发点击事件
if (Math.abs(deltaX) < mTouchSlop && Math.abs(deltaY) < mTouchSlop && time < mClickTimeout) {
//获取事件触发的x轴区域 主要用于区分是左边还是右边
float clickX = event.getX();
//如果是在左边
if (clickX > boundsWidth) {
if (mProgress == 1.0f) {
return false;
} else {
animateToState(true);
}
} else {
if (mProgress == 0.0f) {
return false;
} else {
animateToState(false);
}
}
return false;
} else {
boolean nextStatus = getProgress() > 0.5f;
animateToState(nextStatus);
}
break;
}
return true;
}
通过滑动的距离来计算性别选着Drawable的绘制范围 :
全局创建了一个mProgress 用于计算性别选择Drewable的绘制范围 和颜色渐变的过程 当mProgress =1时 在右边 mProgress=0时在左边
public void setProcess(float progress) {
LogUtils.e("setProcess(GenderSwitchView.java:141)进度" + progress);
float tp = progress;
if (tp > 1) {
tp = 1;
} else if (tp < 0) {
tp = 0;
}
updatePaintStyle(tp);
this.mProgress = tp;
bundsX = (int) (mProgress * boundsWidth);
bounds.left = bundsX;
bounds.right = boundsWidth + bundsX;
genderDrawable.setBounds(bounds);
invalidate();
}
通过滑动距离来计算颜色的渐变 这里用到颜色范围计算的api ArgbEvaluator
:
private void updatePaintStyle(float tp) {
int startColor = (int) (argbEvaluator.evaluate(tp, girlStartColor, boyStartColor));
int endColor = (int) (argbEvaluator.evaluate(tp, girlEndColor, boyEndColor));
LinearGradient linearGradient = new LinearGradient(0, 0, boundsWidth, height, startColor, endColor, Shader.TileMode.REPEAT);
//将计算好的 颜色范围 重新设置到Drawable
genderDrawable.getPaint().setShader(linearGradient);
}
使用ValueAnimator
来处理点击事件的动画效果:
protected void animateToState(boolean checked) {
float progress = mProgress;
if (mProgressAnimator == null) {
return;
}
if (mProgressAnimator.isRunning()) {
mProgressAnimator.cancel();
mProgressAnimator.removeAllUpdateListeners();
}
mProgressAnimator.setDuration(mAnimationDuration);
if (checked) {
//右边
mProgressAnimator.setFloatValues(progress, 1f);
} else {
//左边
mProgressAnimator.setFloatValues(progress, 0.0f);
}
mProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mProgress = (float) animation.getAnimatedValue();
//通过ValueAnimator 进度更新 Drawable 渐变色范围
updatePaintStyle(mProgress);
bundsX = (int) (mProgress * boundsWidth);
bounds.left = bundsX;
bounds.right = boundsWidth + bundsX;
//更新性别选择Drawable的绘制范围
genderDrawable.setBounds(bounds);
//绘制
postInvalidate();
}
});
mProgressAnimator.start();
}
到这里所有事件相关的工作都做完了 看看效果:
剩下就是一些其他细节需求 最外层的文字 和标示图片等 另外文字的绘制需要计算BaseLine
也就是绘制基准线:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//计算图片绘制的 x,y
drawBitmapX = SizeUtils.dp2px(22);
int textMargin = SizeUtils.dp2px(5);
drawBitmapY = (height - girlSign.getHeight()) / 2;
String mText = "男士";
Rect bounds = new Rect();
//测量文字的宽度
selectTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
//获取文字的高度
int textHeight = bounds.height();
//计算文字绘制的 x,y
drawTextX = drawBitmapX + girlSign.getWidth() + textMargin + bounds.width() / 2;
drawTextY = height / 2 + textHeight / 2;
}
最后一同绘制 其中文字颜色的变化 和图标的变化全都集中在更新性别选择Drawable 颜色渐变函数中 处理 这里不再贴代码了:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
backgroundDrawable.draw(canvas);
genderDrawable.draw(canvas);
canvas.drawBitmap(girlSign, drawBitmapX, drawBitmapY, bitmapPaint);
canvas.drawBitmap(boySign, width / 2 + drawBitmapX, drawBitmapY, bitmapPaint);
canvas.drawText("女士", drawTextX, drawTextY, selectTextPaint);
canvas.drawText("男士", width / 2 + drawTextX, drawTextY, defaultTextPaint);
}
最终效果:
总结:在所有的自定义SwitchView 基础上都少不少触摸事件的处理 所以掌握触摸事件的处理情况下 剩下的各种花样需求都万变不离其宗 最后给上完整源码地址SwitchView 希望可以帮助到更多的人