注解
参考资料:
http://www.jianshu.com/p/dce26aa75060
http://www.jianshu.com/p/2a0f883b5aed
http://blog.csdn.net/asialiyazhou/article/details/53055460
http://www.jianshu.com/p/9e34defcb76f
http://www.jianshu.com/p/745655cb431a
注解分为两类:编译时注解和运行时注解。
运行时注解
通常采用反射来实现,由于注解在运行时进行会影响效率
1.注册注解类
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ViewInject{ int value(); }
2.通过反射获取注解值
public class AnnotateUtils { public static void injectViews(Activity activity) { Class<? extends Activity> object = activity.getClass(); // 获取activity的Class Field[] fields = object.getDeclaredFields(); // 通过Class获取activity的所有字段 for (Field field : fields) { // 遍历所有字段 // 获取字段的注解,如果没有ViewInject注解,则返回null // if (field.isAnnotationPresent(InjectView.class)) {} ViewInject viewInject = field.getAnnotation(ViewInject.class); if (viewInject != null) { // 获取字段注解的参数,这就是我们传进去控件Id int viewId = viewInject.value(); if (viewId != -1) { try { // 获取类中的findViewById方法,参数为int Method method = object.getMethod("findViewById", int.class); // 执行该方法,返回一个Object类型的View实例 Object resView = method.invoke(activity, viewId); field.setAccessible(true); // 把字段的值设置为该View的实例 field.set(activity, resView); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } } }
3.使用注解
`
@ViewInject(R.id.buy)
private Button buy;
@ViewInject(R.id.money)
private TextView money;
@ViewInject(R.id.tv_power)
private TextView power;
@ViewInject(R.id.tv_life)
private TextView life;
@ViewInject(R.id.tv_dex)
private TextView dex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnnotateUtils.injectViews(this);
}
`
编译时注解
编译时注解采用apt+