限制方法接受 ContextCompat 解析的资源
Restrict method to accept resource resolved by ContextCompat
我有一个模型,其中一位设置者期待 Color Resource but it is not to able use said resource directly without it being resolved (by making use of ContextCompat)。
有什么方法可以将我的方法注释为 indicate/restrict 这个吗?
public class SimpleModel {
private String name;
private int bgColor;
private int bgImage;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getBgColor() {
return bgColor;
}
public void setBgColor(@ColorInt final int bgColor) {
this.bgColor = bgColor;
}
public int getBgImage() {
return bgImage;
}
public void setBgImage(@DrawableRes final int bgImage) {
this.bgImage = bgImage;
}
}
我知道 @ColorRes
and @ColorInt
-- 但他们没有完全解决我的问题。
这是注释可以为我处理的事情吗? JavaDocs 呢?
如果不是——我如何检查传递的资源是否可用?
@ColorRes
表示要求参数为颜色资源ID。
@ColorInt
实际上是 @!ColorRes
,如果可以使用注释应用 "not" 运算符。它表示要求参数是 int
而不是颜色资源 ID。
因此,您的 public void setBgColor(@ColorInt final int bgColor)
方法应产生以下结果:
model.setBgColor(R.color.red)
:Lint 错误
model.setBgColor(getColor(R.color.red))
:没有错误
model.setBgColor(ContextCompat.getColor(this, R.color.red))
:没有错误
如果出于某种原因,您需要区分后两种情况...我认为没有办法做到这一点。
我有一个模型,其中一位设置者期待 Color Resource but it is not to able use said resource directly without it being resolved (by making use of ContextCompat)。
有什么方法可以将我的方法注释为 indicate/restrict 这个吗?
public class SimpleModel {
private String name;
private int bgColor;
private int bgImage;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getBgColor() {
return bgColor;
}
public void setBgColor(@ColorInt final int bgColor) {
this.bgColor = bgColor;
}
public int getBgImage() {
return bgImage;
}
public void setBgImage(@DrawableRes final int bgImage) {
this.bgImage = bgImage;
}
}
我知道 @ColorRes
and @ColorInt
-- 但他们没有完全解决我的问题。
这是注释可以为我处理的事情吗? JavaDocs 呢?
如果不是——我如何检查传递的资源是否可用?
@ColorRes
表示要求参数为颜色资源ID。
@ColorInt
实际上是 @!ColorRes
,如果可以使用注释应用 "not" 运算符。它表示要求参数是 int
而不是颜色资源 ID。
因此,您的 public void setBgColor(@ColorInt final int bgColor)
方法应产生以下结果:
model.setBgColor(R.color.red)
:Lint 错误model.setBgColor(getColor(R.color.red))
:没有错误model.setBgColor(ContextCompat.getColor(this, R.color.red))
:没有错误
如果出于某种原因,您需要区分后两种情况...我认为没有办法做到这一点。