第一步是打开Android studio定义界面
import Java.lang.annotation.element type;
import Java.lang.annotation.retention;
import Java.lang.annotation.retention policy;
import Java.lang.annotation.target;
@target(elementtype.method ) )。
@ retention (retention policy.runtime ) )。
公共@ interfaceactionlistener {
公共字符串源() default “nothing”
}
插图:
@Target :评论的作用目标
@Target表示Annotation限定的对象范围。 Annotation是本地变量,如packages、types (类、接口、枚举、Annotation类型)、类型成员、生成方法、成员变量、枚举值)、方法参数和循环变量
@Retention :评论的保存位置
@Retention定义保留此Annotation的时间长度。 有些Annotation只存在于源代码中,并被编译器丢弃。 其他的编译成class文件; 编译为class文件的Annotation可能会被虚拟机忽略,并在装载class时读取。 请注意,Annotation和class在使用上是分离的,因此不会影响class的运行。
2.*注释事件处理程序
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
创建注释事件处理程序,以通过反射检索场景类对象的annotation的source对象。 通过调用source对象的setOnClickListener方法进行事件绑定。
步骤2 :将事件绑定到对象,并添加监听事件
import android.view.View;
import java.lang.reflect.Field;
import Java.lang.reflect.invocation handler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
publicclassactionlistenerinstaller {
publicstaticvoidprocessannotations {
类? client=client.getClass (;
方法:客户端. getdeclaredmethods () )。
//获取指定的Annotation对象
actionlistenerlistener=m.get annotation (action listener.class;
监听器!=null ) {
try {
field f=client.getdeclaredfield (listener.source );
f.setaccessible(true );
//控件对象
objectfocusview=f.get(client );
//addListenr函数添加监听并在发生click事件时调用onBtnClick ()函数
addlistENR(focusview,client,m );
}catch(exceptione ) {
e .打印任务跟踪(;
}
}
}
}
privatestaticvoidaddlistenr (finalobjectfocusview,final Object client,final Method m ) throws Exception {
invocationhandlerhandler=newinvocationhandler {
@Override
publicobjectinvoke(objectproxy,Method method,Object[] args ) throws Throwable {
//场景类是onBtnClick (调用方法
returnm.invoke(client );
}
(;
objectonclicklistenr=proxy.newproxyinstance (null,new class [ ] { view.onclick listener.class ),handler;
methodsetonclicklistenermethod=focus view.getclass (.get method )“setonclicklistener”,view.onclicklistener.Classtener
setonclicklistenermethod.invoke (focus view,onClickListenr );
}
}
插图:
3. 注解应用场景类
步骤3 :在应用注释的场景类中,调用处理器中的processAnnotations方法,通过反射完成click事件的绑定,同时为click事件指定source控件,从而触发事件这样就完成了简单的Android注释APP应用。
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
publicclassmainactivityextendsactivity {
private Button test_btn;
@Override
保护性视频创建(bundlesavedinstancestate )。
super.oncreate (savedinstancestate;
setcontentview (r.layout.activity _ main;
test_BTN=(Button ) findviewbyid(r.id.test_BTN );
actionlistenerinstaller.process annotations (this;
}
@ action listener (source=“test _ BTN”)。
公共void onbtnclick (
Android.util.log.d(「czh”,“发生了CLICK事件”
}
}
插图:
执行结果插图:
在首选项中使用Android注释之前,必须导入相关包。
compile‘com.Android.support 3360 support-annotations 3360 latest.integration’