andriod 注解找控件 简单步骤

来源:互联网 发布:wmware 怎么安装mac os 编辑:程序博客网 时间:2024/06/10 01:52

一般情况下我们开发Android应用,初始化控件使用findViewById(),可是一个项目开发完毕,你会发现很多这样的代码,其实是重复的。这个时候你就会发现Java自带的注释(Annotation)是多么的方便了。
一、设计一个ContentView的注释

因为这个注释我们要运在Activity类上,所以我们要申明@ElementType.TYPE。

     @Target(ElementType.TYPE)     @Retention(RetentionPolicy.RUNTIME)     public @interface ContentView {    int value();    }

二、设计一个ContentWidget的注释

因为这个注释我们要运在类的成员变量上,所以我们要申明
@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();// 该类是否存在ContentView类型的注解if (classType.isAnnotationPresent(ContentView.class)) {// 返回存在的ContentView类型的注解ContentView annotation = classType.getAnnotation(ContentView.class);try {// 返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。Method method = classType.getMethod("setContentView", int.class);method.setAccessible(true);int resId = annotation.value();method.invoke(object, resId);} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 返回 Field 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的成员变量,// 包括公共、保护、默认(包)访问和私有成员变量,但不包括继承的成员变量。Field[] fields = classType.getDeclaredFields();if (null != fields && fields.length > 0) {for (Field field : fields) {// 该成员变量是否存在ContentWidget类型的注解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) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.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);        // setContentView(R.layout.activity_main);        ViewUtils.injectObject(this, this);        textView.setText("自定义注释");    }

虽然前期准备的工作有点多,但后序我们的开发过程中对于加载布局和初始化控件会省事不少,这个对于大型项目来说,尤为重要,磨刀不误砍材工!

0 0
原创粉丝点击