xUtils支持View的21个事件注解,如下:
这里选择OnClick举例:
OnClick注解定义:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(
listenerType = View.OnClickListener.class,
listenerSetter = "setOnClickListener",
methodName = "onClick")
public @interface OnClick {
int[] value(); //value是数组,可以在注解中输入多个控件ID.
int[] parentId() default 0;
}
ViewUtils中的注解部分:
// inject event
Method[] methods = handlerType.getDeclaredMethods();
if (methods != null && methods.length > 0) {
for (Method method : methods) {
Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations != null && annotations.length > 0) {
for (Annotation annotation : annotations) {
Class<?> annType = annotation.annotationType();
if (annType.getAnnotation(EventBase.class) != null) {
method.setAccessible(true);
try {
// ProGuard:-keep class * extends java.lang.annotation.Annotation { *; }
Method valueMethod = annType.getDeclaredMethod("value");
Method parentIdMethod = null;
try {
parentIdMethod = annType.getDeclaredMethod("parentId");
} catch (Throwable e) {
}
Object values = valueMethod.invoke(annotation);
Object parentIds = parentIdMethod == null ? null : parentIdMethod.invoke(annotation);
int parentIdsLen = parentIds == null ? 0 : Array.getLength(parentIds);
int len = Array.getLength(values);
for (int i = 0; i < len; i++) {
ViewInjectInfo info = new ViewInjectInfo();
info.value = Array.get(values, i);
info.parentId = parentIdsLen > i ? (Integer) Array.get(parentIds, i) : 0;
EventListenerManager.addEventMethod(finder, info, annotation, handler, method);
}
} catch (Throwable e) {
LogUtils.e(e.getMessage(), e);
}
}
}
}
}
}
使用方法:
@ContentView(R.layout.activity_main)
public class MainActivity extends Activity {
@OnClick({ R.id.tv1_include, R.id.tv2_include })// 注意输入值是数组形式
public void OnClick(View view) {
switch (view.getId()) {
case R.id.tv1_include:
Toast.makeText(getApplicationContext(), "1 clicked~", Toast.LENGTH_SHORT).show();
break;
case R.id.tv2_include:
Toast.makeText(getApplicationContext(), "2 clicked~", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewUtils.inject(this);
}
}