一、先解释一下注解
大家看到下面代码知道BindView是我们自己写的注解,但是他还有注解,而这样的注解我们叫做元注解,所谓元注解解释负责注解其他注解的注解,哈哈,是不是感觉有点绕口,但是事实就是这样的。
下面就讲一下java5.0定义的元注解:
1.@Target
2.@Retention
3.@Documented
4.Inherited
@Target:
@Target说明了Annotation所修饰的范围:Annotation可被用于Packages、Types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。
@Retention:
表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
@Inherited:
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
@Documented:
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
大概讲解了一下注解,就可以更加清晰的认识一下我们自己写的BindView了。
二、下面就是上代码了:
@Target(ElementType.Field)
@Retention(RetentionPolicy.Runtime)
public @interface BindView{
int id;
boolean click() default false;
}
public class AnnotationUtils{
public static void injectView(Object obj,View rootView){
Field[] fields = obj.getClass().getDeclareDFields();
if(fields!=null&&fields.length>0){
for(int i=0;i<fields.length;i++){
Field field = fields[i];
BindView bindView = field.getAnnotation(BindView.class);
if(bindView!=null){
int id = bindView.id();
boolean click = bindView.click();
field.setAccessible(true);
try{
if(click){
rootView.findViewById(id).setOnClickListener((View.OnClickListener)obj);
}
field.set(obj,rootView.findView(id));
}catch(Exception e){
}
}
}
}
}
public static injectView(Activity activity){
injectView(activity,activity.getWindow().getDecorView());
}
@TargetApi(11)
public static injectView(Fragment fragment){
injectView(framgent,fragment.getActivity().getWindow().getDecorView);
}
}
//下面就是BindView的应用
public class MainActivity extends Activity{
@BindView(id=R.id.text)
private TextView text;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnnotationUtils.injectView(this);
}
}