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.


当前回答

你应该做两件事,首先清理项目(在build菜单中)-它会删除build目录,这可能是罪魁祸首:

接下来,同步项目与Gradle文件(在文件下):

这是在Windows 10上的Android Studio 3.6.1中项目的位置。

如果所有这些都失败了,无效缓存和重新启动(在文件下)通常可以做到这一点。在我看来,这将关闭整个程序并占用大量时间。

澄清一下,我是在windows 10上运行这个程序,但它应该也能在MacOS和Linux上运行。

其他回答

有一件事每次都对我有效:

转到——> build。你项目的gradle (Module: app)文件——>做一点改变(例如:把一个<空格>放在某个地方,然后把它移回来)——>然后android studio会要求你同步你的gradle文件——>在文件的右上角——>选择“立即同步”。

在同步完成后,它将解决大多数情况下的问题。

我也有这个问题。简单的“gradlew clean”和“gradlew build”就成功了。


点击Build->Clean Project,将执行gradle Clean

检查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文件并清除项目。

在将gradle插件从1.3.1版本升级到

classpath group: 'com.android.tools.build', name: 'gradle', version: '2.2.1'

它迫使我改变了所有的引用,比如

import [applicationId].R;

to

import [package].R;

在我的库项目中,appcontext.getPackageName();停止正常工作。我用它来获得正确的应用程序资源通过反射,但升级gradle插件后,它开始返回特定口味的applicationId,而不是包…你可以在这里阅读更多相关内容。

您只需要检查Xml文件。 如果出现错误,则无法解决此错误。 只需解决xml错误,然后尝试。

OR

清理你的项目从构建->清洁