一般情况下我们开发Android应用,初始化控件使用findViewById(),可是一个项目开发完毕,你会发现很多这样的代码,其实是重复的。这个时候你就会发现Java自带的注释(Annotation)是多么的方便了。
一、设计一个ContentView的注释
因为这个注释我们要运在Activity类上,所以我们要申明@Targrt(ElementType.TYPE)。
-
@Target(ElementType.TYPE)
-
@Retention(RetentionPolicy.RUNTIME)
-
-
public @interface ContentView {
-
value();
-
}
二、设计一个ContentWidget的注释
因为这个注释我们要运在类的成员变量上,所以我们要申明@Targrt(ElementType.FILELD)。类成员变量指定我们申明的控件对象
-
@Target(ElementType.FIELD)
-
@Retention(RetentionPolicy.RUNTIME)
-
public @interface ContentWidget {
-
int value();
-
}
三、设计一个工具类来提取并处理上述自定义的Annotation类的信息
-
public static void injectObject(Object object, Activity activity) {
-
-
Class<?> classType = object.getClass();
-
-
-
if (classType.isAnnotationPresent(ContentView.class)) {
-
-
ContentView annotation = classType.getAnnotation(ContentView.class);
-
-
-
try {
-
-
-
-
Method method = classType
-
.getMethod("setContentView", int.class);
-
method.setAccessible(true);
-
int resId = annotation.value();
-
method.invoke(object, resId);
-
-
-
} catch (NoSuchMethodException e) {
-
-
e.printStackTrace();
-
} catch (IllegalArgumentException e) {
-
-
e.printStackTrace();
-
} catch (IllegalAccessException e) {
-
-
e.printStackTrace();
-
} catch (InvocationTargetException e) {
-
-
e.printStackTrace();
-
}
-
-
-
}
-
-
-
-
-
Field[] fields = classType.getDeclaredFields();
-
-
-
if (null != fields && fields.length > 0) {
-
-
-
for (Field field : fields) {
-
-
if (field.isAnnotationPresent(ContentWidget.class)) {
-
-
-
ContentWidget annotation = field
-
.getAnnotation(ContentWidget.class);
-
int viewId = annotation.value();
-
View view = activity.findViewById(viewId);
-
if (null != view) {
-
try {
-
field.setAccessible(true);
-
field.set(object, view);
-
} catch (IllegalArgumentException e) {
-
-
e.printStackTrace();
-
} catch (IllegalAccessException e) {
-
-
e.printStackTrace();
-
}
-
}
-
-
-
}
-
-
-
}
-
-
-
}
-
-
-
}
四、在Activity类中我们该怎么使用我们定义的注释
-
@ContentView(R.layout.activity_main)
-
public class MainActivity extends Activity {
-
-
@ContentWidget(R.id.tv)
-
private TextView textView;
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
-
ViewUtils.injectObject(this, this);
-
-
textView.setText("自定义注释");
-
}
虽然前期准备的工作有点多,但后序我们的开发过程中对于加载布局和初始化控件会省事不少,这个对于大型项目来说,尤为重要,磨刀不误砍材工!
DEMO 地址
(一)Android使用自定义注解来初始化控件
原文:http://blog.csdn.net/lee_duke/article/details/39505631