2017-02-16 29 views
0

我有一個StringDef註釋的接口如何在Parcelable中包含用@StringDef註釋的字段?

@StringDef({ 
    SpecialString.A, 
    SpecialString.B 
}) 
@Retention(RetentionPolicy.SOURCE) 
public @interface SpecialString { 
    String B = "BBB"; 
    String A = "AAA"; 
} 

這是我在一個parcelable對象

public class MyParcelable implements Parcelable { 

    private final @SpecialString String mType; 

    protected MyParcelable (Parcel in) { 
     //Android studio shows an error for this line declaring 
     //"Must be one of SpecialString.A, SpecialString.B" 
     mType = in.readString(); 
    } 

    ... 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(mType); 
    } 

} 

我如何處理parceling不訴諸與//noinspection WrongConstant抑制由@StringDef註釋字符串中的字段使用?

+1

您無法將實際字符串寫入'Parcel'。相反,寫一些其他的東西(例如'int')來決定在Parcel中讀取哪一個字符串(例如,通過'switch'語句)。就我個人而言,我只是與'noinspection'一起生活。這些Lint檢查的複雜程度是有限的。 – CommonsWare

+0

正是這個問題導致我意識到,我沒有從中受益,因爲選擇使用@StringDef而不是最終的靜態字符串。爲什麼你選擇使用顯式註釋的字符串有什麼特別的理由嗎? –

+0

這似乎是一個很好的方法來強制執行只傳遞給庫項目的正確值,而不使用枚舉。我認爲沒有檢查條款的成本太高,但我認爲會有更清晰的解決方案 –

回答

0

StringDef字段受Parcelable支持,但目前無法確保值回讀是可接受的值之一。

的方法可以安全地在Android Studio中加入註釋noinspection WrongConstant

更安全的替代忽略可能是使用枚舉,並與MyEnum.valueOf(readString)閱讀或CommonsWare建議,寫一個int序或恆定的,而不是字符串並在讀取值時執行查找。

相關問題