Android - 类型 ID 的预期资源 [英] Android - Expected Resource of type ID

查看:27
本文介绍了Android - 类型 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 调用为

  titleView.setId(View.generateViewId());

  sv.setId(View.generateViewId());

API<17

  1. 打开项目的res/values/文件夹
  2. 创建一个名为 ids.xml
  3. 的 xml 文件
  1. open your project's res/values/ folder
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆