In every instance in all of my classes where I reference R.id.something, the R is in red and it says "cannot resolve symbol R". Also every time there is R.layout.something it is underlined in red and says "cannot resolve method setContentView(?)". The project always builds fine. It is annoying to see this all the time. I have read many other questions on here about something similar but most involved importing projects from Eclipse. I am using what I believe to be the most recent version of Android Studio and the project was created with Android Studio and worked without any "cannot resolve R" problems. I would like to know what causes this if anyone knows.


当前回答

我也遇到过同样的问题,大多数时候都是通过

同步项目与gradle文件 做构建->清洁项目 Doing File ->使缓存失效

但这一次,即使在做了所有这些事情后,错误仍然存在,最后我找到了罪魁祸首。

问题是在一个xml文件,在那里我给了一个普通的字符串值为android:id而不是id资源类型。

错误

android:id="username"

修正

android:id="@id/username"

混淆xml文件中与资源相关的内容是一个主要问题 此错误的原因。注意,它可能不会在xml布局文件中显示为错误。

请注意

在大多数情况下,编译器会在消息中显示错误的来源。 在尝试其他解决方案之前,请先检查它

其他回答

尝试确保完整的包名在第一行。假设您有一个名为LoginActivity.java的文件和一个名为com.domainname.project的包。

java的第一行应该是

package com.domainname.project;

这相当于在dot.net中指定“namespace”。还要确保该包与包含*.java文件的包匹配。

大多数情况下,此问题是由XML文件引起的,请查看XML文件,查找任何错误。

检查xml文件。 清洁项目。

就是它了。

例如,我在strings.xml中有一个条目:

<string name="A">Some text</string>

在activity_main.xml中,我使用了这个字符串条目

<TextView
android:id="@+id/textViewA"
android:text="@string/A"/>

当我一直在做这个项目的时候,我把它删除了

 <string name="A">Some text</string>

因此activity_main.xml就无效了。结果:不能解析R。

因此,检查您的*.xml文件并清除项目。

在我的案例中,通过将Android Studio从3.1更新到3.3解决了这个问题

要更新您的Android Studio:文件->设置->系统设置->更新,然后点击立即检查。

在我的情况下,我需要修复我的布局XML文件中的一些错误。没有指示文件包含错误的图标。然而,当我点击它们时,我注意到一些红线。修好后,找到了R。