2017-04-11 25 views
1

https://developer.android.com/reference/android/support/annotation/IntDef.html的Android @IntDef一個局部變量例

我正在尋找一個例子,如何定義一個局部變量。

我看到如何創建一個函數返回,一個成員變量,一個函數參數,但沒有例子使用Android註釋元素@IntDef來分配一個局部變量。

感謝

UPDATE

這裏有什麼是不工作的一個例子。這是否與放置@Retention的位置有關?我不明白編譯器知道如何將保留策略應用於。這是一個全球性的設置嗎?

int foobar() { 
     @IntDef({ 
       ItemType.TYPE1, 
       ItemType.TYPE2 
     }) 
     @Retention(RetentionPolicy.SOURCE) 
     @interface ItemType { 
      int TYPE1 = 0; 
      int TYPE2 = 1; 
     } 


     @ItemType int type = TYPE1; 
... 
} 

另一個例子,不爲我工作:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

    final @View.MeasureSpec.MeasureSpecMode int heightMode = MeasureSpec.getMode(heightMeasureSpec); 

... 
+0

如果你想使用'@ IntDef'避免枚舉 - [你可能要重新考慮(HTTPS: //publicobject.com/2015/09/30/enumsmatter/「AKA #enumsmatter」)。無論如何,這是由proguard完成的優化,因此如果它傷害到您的生產力並且/或使您的代碼不易讀,則無需爲此煩惱。 –

回答

1
@IntDef({ 
    ItemType.TYPE1, 
    ItemType.TYPE2 
}) 
public @interface ItemType { 
    int TYPE1 = 0; 
    int TYPE2 = 1; 
} 

// use it in global variable like 
@ItemType 
private int type; 

// use it in local variable like 
public void add(@ItemType int type){ 

} 
+0

@ItemType private int type; - 這應該有「私人」嗎?我得到了一個錯誤。 – Mitch