Android kotlin使用注解实现防按钮连点功能的示例
程序员文章站
2022-07-10 15:19:44
singleclick:@retention(annotationretention.runtime)@target(annotationtarget.function)annotation clas...
singleclick:
@retention(annotationretention.runtime) @target(annotationtarget.function) annotation class singleclick( // 点击间隔时间,毫秒 val value: long = 500 )
singleclickaspect:
import android.os.systemclock import org.aspectj.lang.proceedingjoinpoint import org.aspectj.lang.annotation.around import org.aspectj.lang.annotation.aspect import org.aspectj.lang.annotation.pointcut import org.aspectj.lang.reflect.methodsignature @aspect class singleclickaspect { /** * 定义切点,标记切点为所有被@singleclick注解的方法 * 注意:这里 你的包名.singleclick 需要替换成 * 你自己项目中singleclick这个类的全路径 */ @pointcut("execution(@你的包名.singleclick * *(..))") fun methodannotated() { } /** * 定义一个切面方法,包裹切点方法 */ @around("methodannotated()") @throws(throwable::class) fun aroundjoinpoint(joinpoint: proceedingjoinpoint) { try { // 取出方法的注解 val signature = joinpoint.signature as methodsignature val method = signature.method // 检查方法是否有注解 val hasannotation = method != null && method.isannotationpresent(singleclick::class.java) if (hasannotation) { // 计算点击间隔,没有注解默认500,有注解按注解参数来,注解参数为空默认500; val singleclick = method.getannotation(singleclick::class.java) val interval = singleclick.value // 检测间隔时间是否达到预设时间并且线程空闲 if (canclick(interval)) { joinpoint.proceed() } } else { joinpoint.proceed() } } catch (e: exception) { // 出现异常不拦截点击事件 joinpoint.proceed() } } // 判断是否响应点击 private fun canclick(interval: long): boolean { val time = systemclock.elapsedrealtime() val timeinterval = math.abs(time - mlastclicktime) if (timeinterval > interval) { mlastclicktime = time return true } return false } companion object { // 最后一次点击的时间 private var mlastclicktime: long = 0 } }
build.gradle(项目):
buildscript { dependencies { classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.4' } }
build.gradle(app):
plugins { id 'android-aspectjx' }
使用:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <textview android:onclick="ontextclick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world!" app:layout_constraintbottom_tobottomof="parent" app:layout_constraintleft_toleftof="parent" app:layout_constraintright_torightof="parent" app:layout_constrainttop_totopof="parent" /> </androidx.constraintlayout.widget.constraintlayout>
class mainactivity : appcompatactivity() { override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) setcontentview(r.layout.activity_main) } @singleclick(800) fun ontextclick(view: view) { } }
以上就是android kotlin使用注解实现防按钮连点功能的示例的详细内容,更多关于android kotlin实现防按钮连点功能的资料请关注其它相关文章!