Android-注解详解
背景
上一章,我们研究了 Java注解 的用法;紧跟着这章研究一下Android相关的注解的使用,比如我们熟悉的ButterKnife就是使用注解的方式实现对其使用,掌握注解的使用方法极大的方便了我们的开发效率
环境
使用Android注解前需要导入相关的包
compile 'com.android.support:support-annotations:latest.integration'
注意:如果我们已经引入了appcompat则没有必要再次引用support-annotations,因为appcompat默认包含了对其引用
使用
Android注解给我们提供了三种主要和其他注释供我们使用:
IntDef和StringDef注解;
资源类型注解;
Null注解;
其他实用注解
IntDef和StringDef注解替代枚举
这里我们采用假设一个问题然后一步步解决学习:假设有一个User对象,我们需要记录user类型的变量,如何实现呢?
方案一
public class UserI {
public static int childe=0x1;
public static int man=0x2;
public static int girl=0x3;
private int userType;
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
}
估计大家常用的就是这样的方式去解决这样的需求,但是上述实现存在一个问题:setUserType
设置的是一个int
类型的变量,既然如此我们可以如此调用:
UserI userI=new UserI();
/*正确调用*/
userI.setUserType(userI.childe);
/*错误调用*/
userI.setUserType(100);
错误方式下的调用也不会抛出异常,所以这样的实现方式存在逻辑泄漏的危险!
方案二
既然如此:想必这个时候大家想到的解决办法就是枚举了,下面研究下枚举的实现
public class UserE {
private UserEmun userType;
public UserEmun getUserType() {
return userType;
}
public void setUserType(UserEmun userType) {
this.userType = userType;
}
public static enum UserEmun {
childe,
man,
girl
}
}
调用:
UserE userE=new UserE();
userE.setUserType(UserE.UserEmun.childe);
从实现方式和逻辑上看,方案二枚举确实能解决方案一存在的漏洞,但是这里有一点需要注意:Enum
因为其相比方案一的常量来说,占用内存相对大很多而受到曾经被Google
列为不建议使用。
既然枚举也有它相关的缺陷,那如何完美解决这样的需求呢,以下完美实现-就是Android
中用注解来替换java
的枚举;
完美方案
Android中
新引入的替代枚举的注解有IntDef
和StringDef
,他们唯一的区别一个是int
类型,一个是string
类型,下面我们就以IntDef
为例讲解如何使用
构建定义注解
public class UserInter {
public static final int childe = 0x1;
public static final int man = 0x2;
public static final int girl = 0x3;