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

我们都知道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方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容