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.


当前回答

在我的例子中,当我试图从另一个包调用R时,出现了这个错误。导入R包解决了我的问题。

import com.mtdaps.yourapp.R;

其他回答

我也遇到了这个问题,我用这种方法解决了它。 首先进入Gradle,点击clean。 其次,单击Build。

确保不要从android studio清洁

如果你在移动java文件或目录到其他位置后看到这个错误,那么你可以保证Android Studio已经混淆了。你猜怎么着?撤销这些操作并不能解决问题。

所以你试着戒毒,但没用。

重启也不行。

但是试试文件->无效缓存/重新启动…->失效并重启

Android Studio维护哪些文件依赖于哪些其他文件的信息。由于移动文件没有正确实现,因此移动文件会导致错误。这还不是全部:这些依赖项的缓存被用于加速构建。

这意味着您不仅必须重新启动,而且还需要使这些缓存失效以恢复(或者更准确地说,重新构建)正常运行。

在将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,而不是包…你可以在这里阅读更多相关内容。

在最新版本的Android Studio中,至少对我来说,如下作品:

“工具”->“Android”->“同步项目与Gradle文件”

在最新的Android Studio 3.1.3(2018年7月)中,“同步项目与Gradle文件”在主菜单栏中可用。

以上答案都不能解决我的问题。所以我添加了我的解决方案,以防有人遇到类似的问题。在我的构建中。我有gradle依赖,

compile 'com.android.support:appcompat-v7:22+'

我的compilesdk版本是 编译esdkversion 21,所以android工作室不高兴。我简单地更新了我的compilesdkversion到23,并进行了同步。

我还将依赖项更新为

compile 'com.android.support:appcompat-v7:23.1.1'

匹配我的支持库在工具—> Android—> SDK管理器—> SDK工具选项卡—> Android支持库—>版本。 现在一切都好了。快乐编码:)