Android AOP 解决重复点击

引入依赖

在项目的build.gradle中添加classpath

1
classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4'

在模块的build.gradle中添加依赖

1
apply plugin: 'android-aspectjx'

1
implementation 'org.aspectj:aspectjrt:1.8.14'

编写注解

1
2
3
4
5
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SingleClick {
long value() default 2000;//点击间隔时间
}

编写Aspect注解类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@Aspect
public class SingleClickAspect {

private static long mLastClickTime;
private static int mLastClickViewId;


@Pointcut("execution(@com.chu.kit.annotation.SingleClick * *(..))")
public void singleClick() {

}

@Around("singleClick()")
public void aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
View view = null;
for (Object arg : joinPoint.getArgs()) {
if (arg instanceof View) {
view = (View) arg;
break;
}
}
if (view == null) {
return;
}

MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
if (!method.isAnnotationPresent(SingleClick.class)) {
return;
}
SingleClick singleClick = method.getAnnotation(SingleClick.class);

if (!isFastClick(view, singleClick.value())) {
joinPoint.proceed();
}
}

private static boolean isFastClick(View v, long intervalMillis) {
int viewId = v.getId();
long time = System.currentTimeMillis();
long timeInterval = Math.abs(time - mLastClickTime);
if (timeInterval < intervalMillis && viewId == mLastClickViewId) {
return true;
} else {
mLastClickTime = time;
mLastClickViewId = viewId;
return false;
}
}
}

使用注解

  • 设置监听情况下,使用注解方式。

    1
    2
    3
    4
    5
    6
    7
    button1.setOnClickListener(new View.OnClickListener() {
    @Override
    @SingleClick
    public void onClick(View v) {
    showToast("按钮1点击了");
    }
    });
  • 引入butterknife情况下,使用注解方式。

    1
    2
    3
    4
    5
    @SingleClick(3000)
    @OnClick(R.id.button2)
    public void onClick(View view) {
    showToast("按钮2点击了");
    }

最后

打包成library时,除了需要引入libary之外。还需要在项目中对应模块的build.gradle中引用如下代码

1
apply plugin: 'android-aspectjx'

end~

您的支持是我原创的动力