Android 中巧妙使用枚舉類型

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。這種方式比枚舉類的寫法複雜一點,但並沒有什麼難度。請看例子說明:

  1. 創建一個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前面有@。

  2. 其次,如何使用?

    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章