标签:
先贴实现的activity的代码:
@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
@ViewInject(R.id.text_view)
private TextView textView;
@OnClick(R.id.text_view)
private void onClick(View view){
textView.setText("我是click后的textview");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewInjectUtils.inject(this);
textView.setText("我是click前的textview");
}
}
ContentView(类)注解实现:
1、定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContentView {
int value();
}
2、实现注解
Field注解实现
1、定义注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewInject {
int value();
}
2、实现注解
private static void injectView(Activity activity) {
Class<? extends Activity> clazz = activity.getClass();
//获得activity的所有成员变量
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//获得每个成员变量上面的ViewInject注解,没有的话,就会返回null
ViewInject viewInject = field.getAnnotation(ViewInject.class);
if (viewInject != null) {
int viewId = viewInject.value();
View view = activity.findViewById(viewId);
try {
field.setAccessible(true);
field.set(activity, view);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
接口(方法)注解实现
1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OnClick {
int[] value();
}
2、实现注解
public class ViewInjectUtils {
public static void inject(Activity activity) {
injectContentView(activity);
injectView(activity);
injectEvent(activity);
}
private static void injectEvent(final Activity activity) {
Class<? extends Activity> clazz = activity.getClass();
Method[] methods = clazz.getDeclaredMethods();
for (final Method method2 : methods) {
OnClick click = method2.getAnnotation(OnClick.class);
if (click != null) {
int[] viewId = click.value();
method2.setAccessible(true);
Object listener = Proxy.newProxyInstance(View.OnClickListener.class.getClassLoader(),
new Class[]{View.OnClickListener.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method2.invoke(activity, args);
}
});
try {
for (int id : viewId) {
View v = activity.findViewById(id);
Method setClickListener = v.getClass().getMethod("setOnClickListener", View.OnClickListener.class);
setClickListener.invoke(v, listener);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
标签:
原文地址:http://blog.csdn.net/norwaya007/article/details/51361407