我正在使用 View
类的 setId
方法。按照这个方法
public void setId(@IdRes int id) // This will accept resource id
当我尝试将此方法与一些硬编码的 int
值(假设为 100)一起使用时,此方法开始抛出预期的正确警告-
actionButton.setId(100);
Expected resource of type id.
但是当我将这个硬编码值转换为一个方法并且从未定义该方法将返回 @IdRes
时,警告变得无声。
private int getViewId() {
return 100;
}
设置 Id 的方法调用。
actionButton.setId(getViewId());
两者不一样吗?硬编码 int
和 int
从此方法返回。那么为什么在一种情况下方法抛出警告而在另一种情况下它变得沉默。
为了安全起见,我尝试使用 StringRes
,但在这两种情况下我都收到了警告。
private void setMyString(@StringRes int resourceString) {}
以下两种情况下的警告-
setMyString(1);
setMyString(getStringId()); getStringId returns int value
最佳答案
这只是一个 Lint 警告,因为该方法需要一个来自 R.id 类的变量。
对于从方法返回值的情况,Lint 不会费心检查整个函数是返回硬编码整数还是实际 ID。
从@IdRes 的文档中可以看出:
Denotes that an integer parameter, field or method return value is expected to be an id resource reference (e.g. android.R.id.copy).
此外,注释仅存在于文档的源代码中。代码编译完成后,注释将被移除。
关于java - @IdRes 的 Android 注解工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784286/