Android 中巧妙使用枚举类型
众所周知,在Android中并不推荐使用枚举类型,来听听官方的说法:
Android Developer-Avoid enumerations
Avoid enumerations
A single enum can add about 1.0 to 1.4 KB of size to your app’s classes.dex file. These additions can quickly accumulate for complex systems or shared libraries. If possible, consider using the @IntDef annotation and ProGuardto strip enumerations out and convert them to integers. This type conversion preserves all of the type safety benefits of enums.
翻译:每个枚举常量可以使你的应用程序的classes.dex文件增加大约1.0到1.4 KB的大小。 这些额外增加的占用会迅速在你的系统或共享库中累加。如果可能的话Android中推荐使用@IntDef 注解或ProGuard代替。
虽不建议使用枚举类,官方给出了另一种解决方案,那就是使用@IntDef、@StringDef。这种方式比枚举类的写法复杂一点,但并没有什么难度。请看例子说明:
-
创建一个Interface文件
import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @StringDef({BookType.TYPE_COMIC, BookType.TYPE_FICTION, BookType.TYPE_STORE}) public @interface BookType { public static final String TYPE_COMIC = "comic"; public static final String TYPE_FICTION = "fiction"; public static final String TYPE_STORE = "store"; }
这就是Android官方推荐的替代传统枚举的方法,不要忘了Interface前面有@。
-
其次,如何使用?
public Book getBook(@BookType String type) { Book book = null; if (type == BookType.TYPE_COMIC) { /* 操作 */ } else if (type == BookType.TYPE_FICTION) { /* 操作 */ } else if (type == BookType.TYPE_STORE) { /* 操作 */ } return book; } public class Book { public Book(@BookType String type) { } }
可以看出,使用的方法跟传统枚举差不多!
简单小分享 日期:2020-05-12