当我们在写Android代码的时候有时候UI界面上的控件太多代码就特别冗余,findViewById() setOnClickListener()... 郁闷
看看我一般是怎么做的吧~
BindView
@Target(ElementType.FIELD)//表示用在字段上
@Retention(RetentionPolicy.RUNTIME)//表示生命周期为运行时
public @interface BindView {
public int id();
public boolean click() default false;
}
AnnotateUtil
public class AnnotateUtil {
/**
* @param currentClass
* 当前类,一般为Activity或Fragment
* @param sourceView
* 待绑定控件的直接或间接父控件
*/
public static void initBindView(Object currentClass, View sourceView) {
// 通过反射获取到全部属性,反射的字段可能是一个类(静态)字段或实例字段
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();
boolean clickLis = bindView.click();
try {
field.setAccessible(true);
if (clickLis) {
sourceView.findViewById(viewId).setOnClickListener(
(OnClickListener) currentClass);
}
// 将currentClass的field赋值为sourceView.findViewById(viewId)
field.set(currentClass, sourceView.findViewById(viewId));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
* 必须在setContentView之后调用
*
* @param aty
*/
public static void initBindView(Activity aty) {
initBindView(aty, aty.getWindow().getDecorView());
}
/**
* 必须在setContentView之后调用
*
* @param view
* 侵入式的view,例如使用inflater载入的view
*/
public static void initBindView(View view) {
Context cxt = view.getContext();
if (cxt instanceof Activity) {
initBindView((Activity) cxt);
} else {
throw new RuntimeException("view must into Activity");
}
}
/**
* 必须在setContentView之后调用
*
* @param frag
*/
public static void initBindView(Fragment frag) {
initBindView(frag, frag.getActivity().getWindow().getDecorView());
}
}
哈哈 是不是很简单,想怎么用就怎么用