我有这个代码
final static int TITLE_ID = 1;
final static int REVIEW_ID = 2;
现在,我想在我的主类中创建一个新布局
public View createContent() {
// create linear layout for the entire view
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.VERTICAL);
// create TextView for the title
TextView titleView = new TextView(this);
titleView.setId(TITLE_ID);
titleView.setTextColor(Color.GRAY);
layout.addView(titleView);
StarView sv = new StarView(this);
sv.setId(REVIEW_ID);
layout.addView(sv);
return layout;
}
但是当我调用 TITLE_ID 和 REVIEW_ID 时,它会给我一个错误
Supplying the wrong type of resource identifier.
For example, when calling Resources.getString(int id), you should be passing R.string.something, not R.drawable.something.
Passing the wrong constant to a method which expects one of a specific set of constants. For example, when calling View#setLayoutDirection, the parameter must be android.view.View.LAYOUT_DIRECTION_LTR or android.view.View.LAYOUT_DIRECTION_RTL.
运行此代码没有任何问题。我只是想知道为什么它会给我一个错误。有什么想法吗?
最佳答案
这不是编译器错误。这只是编辑器验证错误(lint 警告),因为这不是处理 Ids 的常用方法。
因此,如果您的应用支持 API 17 及更高版本,
您可以调用View.generateViewId作为
titleView.setId(View.generateViewId());
和
sv.setId(View.generateViewId());
对于 API<17
- 打开项目的
res/values/
文件夹 - 创建一个名为
ids.xml
的 xml 文件
内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="titleId" type="id" />
<item name="svId" type="id" />
</resources>
然后在你的代码中,
titleView.setId(R.id.titleId);
和
sv.setId(R.id.svId);
并禁用此警告(如果需要)
在 Android Studio 中单击与此“错误”一致的灯泡。并在第一个子菜单中选择禁用检查。
关于java - Android - 类型 ID 的预期资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696879/