本章目录
- Part One:自定义View的点击事件
- Part Two:点击事件处理
自定义View的点击事件
官方的源生控件都有自己的点击或者触摸监听事件,那我们的自定义View也可以设置自己独有的监听器。
监听器的原理其实就是接口回调,我们在异步的网络请求或者MVC模式中会经常遇到,并不复杂。
点击事件处理
- 跟自定义View无关的外部监听,比如像Button一样点击跳转之类的可以直接在Activity里设置OnClickListener。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = findViewById(R.id.mainActivity_container);
CustomCircleView customCircleView = findViewById(R.id.circleView);
customCircleView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(relativeLayout, "点击了", Toast.LENGTH_SHORT).show();
}
});
}
}
效果为:
- 如果希望既能处理外部事件,同时内部也有一些变化,比如Button按钮点击是会有个摁下抬起的动作。那该怎么做呢,很简单,重写performClick()方法即可,在里面填写自定义View内部变化逻辑。
@Override
public boolean performClick() {
currentProgress = 0;
invalidate();
return super.performClick();
}
效果为:
- 如果像上述所说那样实现监听,同时又实现了该View的onTouchEvent触摸监听,那么无论触摸监听的返回值是什么,OnClickListener都无法触发了。
@Override
public boolean performClick() {
currentProgress = 0;
invalidate();
return super.performClick();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Toast.makeText(context, "摁下", Toast.LENGTH_SHORT).show();
return true; // 只有返回true这个控件的move和up才会响应
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
Toast.makeText(context, "移动", Toast.LENGTH_SHORT).show();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Toast.makeText(context, "抬起", Toast.LENGTH_SHORT).show();
}
return super.onTouchEvent(event);
}
效果为:
可以看到,重绘的点击监听是没有被执行的。
解决的话,其实很简单,在重写OnTouchEvent的时候,会有一个警告。
很长的一段话,概括一下就是要在触摸监听的逻辑里面调用performClick()方法。比如:
@Override
public boolean performClick() {
currentProgress = 0;
invalidate();
return super.performClick();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Toast.makeText(context, "摁下", Toast.LENGTH_SHORT).show();
return true; // 只有返回true这个控件的move和up才会响应
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
Toast.makeText(context, "移动", Toast.LENGTH_SHORT).show();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
performClick();
Toast.makeText(context, "抬起", Toast.LENGTH_SHORT).show();
}
return super.onTouchEvent(event);
}
这样的话,警告也没了,外部监听,内部两个监听也都实现了,效果为:
最终,本案例所有代码为:
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomCircleView">
<attr name="circleColor" format="color"/>
<attr name="radius" format="dimension"/>
<attr name="strokeWidth" format="dimension"/>
<attr name="progressColor" format="color"/>
</declare-styleable>
</resources>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/mainActivity_container"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.terana.customviewclicklistener.activities.MainActivity">
<com.terana.customviewclicklistener.customview.CustomCircleView
android:id="@+id/circleView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:circleColor="#696969"
app:progressColor="#1E88E5"
app:radius="44dp"
app:strokeWidth="6dp" />
</RelativeLayout >
MainActivity.java:
package com.terana.customviewclicklistener.activities;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.terana.customviewclicklistener.R;
import com.terana.customviewclicklistener.customview.CustomCircleView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = findViewById(R.id.mainActivity_container);
CustomCircleView customCircleView = findViewById(R.id.circleView);
customCircleView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(relativeLayout, "点击了", Toast.LENGTH_SHORT).show();
}
});
}
}
CustomCircleView:
package com.terana.customviewclicklistener.customview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.terana.customviewclicklistener.R;
import com.terana.customviewclicklistener.utils.DensityUtils;
public class CustomCircleView extends View{
//画圆的画笔
private Paint circlePaint;
//圆的半径
private float radius;
//圆的颜色
private int circleColor;
//圆的宽度
private float strokeWidth;
//动态圆的颜色
private int progressColor;
//动态圆的画笔
private Paint progressPaint;
//动态圆的当前进度值
private int currentProgress;
//动态圆的范围
private RectF initRectF;
//文字画笔
private Paint textPaint;
//为了密度转换,需要一个context
private Context context;
public CustomCircleView(Context context) {
this(context, null);
}
public CustomCircleView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public CustomCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.context = context;
initAttrs(context, attrs);
initVariables();
}
@Override
public boolean performClick() {
currentProgress = 0;
invalidate();
return super.performClick();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Toast.makeText(context, "摁下", Toast.LENGTH_SHORT).show();
return true; // 只有返回true这个控件的move和up才会响应
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
Toast.makeText(context, "移动", Toast.LENGTH_SHORT).show();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
performClick();
Toast.makeText(context, "抬起", Toast.LENGTH_SHORT).show();
}
return super.onTouchEvent(event);
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.CustomCircleView, 0, 0);//获取TypedArray对象
radius = typedArray.getDimension(R.styleable.CustomCircleView_radius,
100);//获取半径,默认值为100
strokeWidth = typedArray.getDimension(R.styleable.CustomCircleView_strokeWidth,
2);//获取圆环的宽度,默认为2
circleColor = typedArray.getColor(R.styleable.CustomCircleView_circleColor,
Color.BLACK);//获取圆环的颜色,默认为红色
progressColor = typedArray.getColor(R.styleable.CustomCircleView_progressColor,
Color.RED);//获取圆环的颜色,默认为红色
typedArray.recycle();//TypedArray对象是共享的资源,所以在获取完值之后必须要调用recycle()方法来回收。
}
private void initVariables() {
//创建画圆的画笔
circlePaint = new Paint();
circlePaint.setAntiAlias(true);//画笔去除锯齿
circlePaint.setColor(circleColor);//画笔颜色为红色
circlePaint.setStyle(Paint.Style.STROKE);//画的圆是空心圆,FILL为实心圆
circlePaint.setStrokeWidth(strokeWidth);//设置圆的线条宽度为2
//创建动态圆的范围
initRectF = new RectF();
//创建动态圆的画笔
progressPaint = new Paint();
progressPaint.setAntiAlias(true);//画笔去除锯齿
progressPaint.setColor(progressColor);//画笔颜色为红色
progressPaint.setStyle(Paint.Style.STROKE);//画的圆是空心圆,FILL为实心圆
progressPaint.setStrokeWidth(strokeWidth);//设置圆的线条宽度为2
//初始化文字画笔
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(circleColor);
textPaint.setStyle(Paint.Style.STROKE);
textPaint.setTextSize(DensityUtils.sp2px(context, 22));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//getSuggestedMinimumWidth用于返回View推荐的最小宽度
int width = getMyMeasureSize(getSuggestedMinimumWidth(), widthMeasureSpec);
//getSuggestedMinimumHeight用于返回View推荐的最小高度
int height = getMyMeasureSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);//必须调用此方法,否则会抛出异常
}
private int getMyMeasureSize(int size, int measureSpec) {
int result = size;
//从MeasureSpec中获取测量模式
int specMode = MeasureSpec.getMode(measureSpec);
//从MeasureSpec中获取测量大小
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode){
//父容器没有对当前View有任何限制,要多大就多大,这种情况一般用于系统内部,表示一种测量状态。
case MeasureSpec.UNSPECIFIED:
result = size;//用推荐值即可
break;
//父容器已经检测出View所需要的精确大小,这个时候View的最终大小就是SpecSize的值。
//对应match_parent和具体的数值。
case MeasureSpec.EXACTLY:
result = specSize;
break;
//父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值。对应wrap_content。
case MeasureSpec.AT_MOST:
result = Math.min(200, specSize);
break;
}
return result;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int minimum = Math.min(getWidth() / 2, getHeight() / 2);
radius = radius <= minimum ? radius : minimum;
//画圆
canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius - strokeWidth / 2, circlePaint);
//动态圆的总进度
int totalProgress = 100;
//获取动态圆的矩形区域
initRectF.top = getWidth() / 2 - radius + strokeWidth / 2;
initRectF.left = getHeight() / 2 - radius + strokeWidth / 2;
initRectF.right = getWidth() / 2 + radius - strokeWidth / 2;
initRectF.bottom = getHeight() / 2 + radius - strokeWidth / 2;
updateProgress();
//本质其实是画一个圆弧形的矩形
canvas.drawArc(initRectF, -90,((float) currentProgress / totalProgress)
* 360 , false, progressPaint);
//在中心点绘制文字
String text = currentProgress + "%";
//获取文字的宽度,text是文本,然后从0开始到文字结束
float textWidth = textPaint.measureText(text, 0, text.length());
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
canvas.drawText(text, (getWidth() - textWidth) / 2,
getHeight() / 2 + (Math.abs(fontMetrics.ascent) - fontMetrics.descent) / 2, textPaint);
}
private MyRunnable runnable = new MyRunnable();
private void updateProgress() {
if (currentProgress == 60){
getHandler().removeCallbacks(runnable);
}else {
getHandler().postDelayed(runnable, 20);
}
}
private class MyRunnable implements Runnable{
@Override
public void run() {
currentProgress++;
postInvalidate();
}
}
public void setRadius(float mRadius) {
this.radius = mRadius;
invalidate();//重绘
}
public void setCircleColor(int mCircleColor) {
circlePaint.setColor(mCircleColor);
invalidate();//重绘
}
public void setStrokeWidth(float mStrokeWidth) {
circlePaint.setStrokeWidth(mStrokeWidth);
invalidate();//重绘
}
}