Android技术知识android收集

告别繁琐的findViewById,在Activity中使用注解

2016-03-03  本文已影响713人  Ryon

我们都知道Android中是通过findViewById()这个方法来绑定xml中的控件的。但是当控件较多时,findViewById()的代码行数也会随之增多,而且这些findViewById函数并没有表示其他特殊的含义。因此,activity中大量重复的findViewById()方法就导致了整个代码看起来很臃肿。

还好,我们可以使用注解的方法来简化findViewById()

第一步,定义我们的注解类:


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewInject {  
    int value() default 0;  
}  

第二步,在activity中增加解析注解方法

public void autoInjectAllField() {  
        try {  
            Class<?> clazz = this.getClass();  
            Field[] fields = clazz.getDeclaredFields();//获得Activity中声明的字段  
            for (Field field : fields) {  
                // 查看这个字段是否有我们自定义的注解类标志的  
                if (field.isAnnotationPresent(ViewInject.class)) {  
                    ViewInject inject = field.getAnnotation(ViewInject.class);  
                    int id = inject.value();  
                    if (id > 0) {  
                        field.setAccessible(true);  
                        field.set(this, this.findViewById(id));//给我们要找的字段设置值  
                    }  
                }  
            }  
        } catch (IllegalAccessException e) {  
            e.printStackTrace();  
        } catch (IllegalArgumentException e) {  
            e.printStackTrace();  
        }  
    } 

第三步 enjoy it!

/**
 *用法示例
 **/

@ViewInject(R.id.tv_main)
TextView text;

参考文章:Android中通过注解代替findViewById方法

上一篇 下一篇

猜你喜欢

热点阅读