2017-04-11 65 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