Android - 类型ID的预期资源 [英] Android - Expected Resource of type ID
问题描述
我有这段代码
final static int TITLE_ID = 1;
final static int REVIEW_ID = 2;
现在,我想在我的主类中创建一个新布局
Now, I want to create a new layout in my main class
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时,它会给我一个错误
But when ever I call TITLE_ID and REVIEW_ID, it gives me an error
提供错误类型的资源标识符。
例如,当调用Resources.getString(int id)时,你应该传递R.string.something,而不是R.drawable.something。
将错误的常量传递给需要一组特定常量的方法。例如,在调用View#setLayoutDirection时,参数必须是android.view.View.LAYOUT_DIRECTION_LTR或android.view.View.LAYOUT_DIRECTION_RTL。
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.
运行此代码时没有任何问题。我只是想知道它为什么会给我一个错误。有什么想法?
I don't have any problem running this code. I'm just wondering why it gives me an error. Any idea?
推荐答案
这不是编译器错误。这只是编辑器验证错误(lint警告),因为这不是处理ID的常用方法。
This is not a compiler error. It is just editor validation error(lint warning) as this is not a common way to deal with Ids.
因此,如果您的应用支持API 17及更高版本,
So if your app supporting API 17 and higher,
您可以致电 View.generateViewId as
titleView.setId(View.generateViewId());
和
sv.setId(View.generateViewId());
和 API< 17
- 打开项目的
res / values /
文件夹 - 创建一个名为xml的文件
ids.xml
- open your project's
res/values/
folder - create an xml file called
ids.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);
并禁用此警告(如果需要)
And to disable this warning (If you want)
在Android Studio中点击灯泡上的错误。并在第一个子菜单中选择禁用检查。
In Android Studio click on light bulb on line with this 'error'. And select Disable inspection in first submenu.
这篇关于Android - 类型ID的预期资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!