1.首先自定义一个注解
@Retention(RetentionPolicy.RUNTIME)//可以在虚拟中执行
@Target(ElementType.FIELD)//作用在属性变量上
public @interface InjectView {
public int id();
}
2.向目标控件加上该注解
@InjectView(id = R.id.main_button)
private Button start;
3.定义一个注解工具类,这里自定一个 InitUtils
public static void bind(Activity activity){//使用静态方法
bindFeild(activity);
}
private static void bindFeild(Activity activity) {
Class<? extends Activity> aClass = activity.getClass();//使用反射机制获取对象
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
InjectView injectView = declaredField.getAnnotation(InjectView.class);
if(injectView!=null){
int id = injectView.id();
View viewById = activity.findViewById(id);
declaredField.setAccessible(true);
try {
declaredField.set(activity,viewById);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
4.最后调用该工具类
InitUtils.bind(this);