Android @IntDef本地变量示例

3

https://developer.android.com/reference/android/support/annotation/IntDef.html

我正在寻找一个定义本地变量的例子。

我知道如何创建函数返回值、成员变量和函数参数,但是没有使用Android注释元素@IntDef分配本地变量的示例。

谢谢。

更新

这里有一个示例不起作用。这是否与放置@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);

...

如果您想使用@IntDef来避免枚举 - 您可能需要重新考虑。这是由Proguard自动完成的优化,因此如果它影响了您的生产力和/或使您的代码不易读懂,那么就没有必要费心去做。 - Dev-iL
1个回答

3
@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){

}

@ItemType 私有 int 类型; - 这个应该加上 "私有" 吗?我加上后出现了错误。 - Mitch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接