Android - Expected Resource of type ID

后端 未结 3 406
小蘑菇
小蘑菇 2020-12-13 04:27

I have this code

final static int TITLE_ID = 1;
final static int REVIEW_ID = 2;

Now, I want to create a new layout in my main class

相关标签:
3条回答
  • 2020-12-13 04:46

    You can also disable lint at build.gradle file. Add these lines in your build.gradle file.

    android { 
           lintOptions{
                 disable "ResourceType"
           }
    }
    
    0 讨论(0)
  • 2020-12-13 05:05

    I am including this as an alternative to "fixing" the issue for those that cannot generate a view ID (ie. defining the ID before the view is actually present) and know what they are doing.

    Directly above a variable declaration or method that contains the issue, simply include @SuppressWarnings("ISSUE_IDENTIFIER") to disable the lint warning for that instance.

    In this case, it would be @SuppressWarnings("ResourceType")

    Using general methods to disable the warning type is bad practice and can lead to unforeseen issues, such as memory leaks and unstable code. Don't publish garbage.

    Make sure to undo the option to Disable inspection and remove these lines from the build.gradle:

    android {
        lintOptions{
            disable "ResourceType"
        }
    }
    
    0 讨论(0)
  • 2020-12-13 05:06

    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.

    So if your app supporting API 17 and higher,

    you can call View.generateViewId as

      titleView.setId(View.generateViewId());
    

    and

      sv.setId(View.generateViewId());
    

    and for API<17

    1. open your project's res/values/ folder
    2. create an xml file called ids.xml

    with the following content:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item name="titleId" type="id" />
        <item name="svId" type="id" />
    </resources>
    

    then in your code,

      titleView.setId(R.id.titleId);
    

    and

      sv.setId(R.id.svId);
    

    And to disable this warning (If you want)

    In Android Studio click on light bulb on line with this 'error'. And select Disable inspection in first submenu.

    0 讨论(0)
提交回复
热议问题