/**
* 注解式绑定控件-类
*/
@Target(ElementType.FIELD) // 表示类成员
@Retention(RetentionPolicy.RUNTIME) // 表示运行时可获取类成员
public @interface BindView {
public int id();
}
/**
* 注解式绑定控件-方法
* para1 当前的类,为Activity或Fragment
*/
public static void initBindView(Object currentClass) {
// 通过反射机制获取到类的全部属性
Field[] fields = currentClass.getClass().getDeclaredFields();
if (fields != null && fields.length > 0) {
for (Field field : fields) {
// 返回BindView类型的注解内容
BindView bindView = field.getAnnotation(BindView.class);
if (bindView != null) {
int viewId = bindView.id();
try {
field.setAccessible(true);
// 将currentClass类中的field赋值为sourceView.findViewById(viewId)
field.set(currentClass, ((Activity) currentClass).findViewById(viewId));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
使用方法:
/**
* 注解式绑定控件声明
*/
@BindView(id = R.id.listview)
private ListView listview;
@BindView(id = R.id.swiperefreshlayout)
private RefreshLayout swipeRefreshLayout;
在onCreate方法中调用:
initBindView(this);
注解式绑定使得代码变得更加简洁,但是反射机制让效率变低。
参考文章地址:
http://mobile.51cto.com/aprogram-449682.htm
http://blog.csdn.net/rain_butterfly/article/details/37931031
http://www.itnose.net/detail/6117657.html
http://www.tuicool.com/articles/f2Y7Rzf