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.


当前回答

考虑以下IDE功能:

用gradle文件同步项目 Build ->清洁项目 Build ->重建项目 File ->使缓存失效


我的简单解决方案是:

Check that there is no error line in the dependencies of the build.gradle of the app or in all the resource files in the /res directory; where some common errors are when the attribute values are left without references when using: "@string/.." "@style/.." Make sure you are not getting an error of the type Android resource linking failed when the project is rebuilt. Open the file that contains the line with the error Cannot resolve symbol 'R' Scrolling to the last line of the class with said error line Click on a position to the right of the closing key } of the class

通过这种方式,IDE警告对话框将执行r类的导入。

GL

其他回答

同样的问题。当我在我的可绘制文件夹中添加了一些图像并试图访问它们时开始。此外,添加的图像有大写字母的扩展名。这似乎使构建崩溃,因为即使我重命名它们,消息也是一样的,R是不可访问的。我所做的是,在.iml文件中,我寻找了excludeFolder并删除了它们(如下图所示):

  <excludeFolder url="file://$MODULE_DIR$/build/apk" />
  <excludeFolder url="file://$MODULE_DIR$/build/assets" />
  <excludeFolder url="file://$MODULE_DIR$/build/bundles" />
  <excludeFolder url="file://$MODULE_DIR$/build/classes" />
  <excludeFolder url="file://$MODULE_DIR$/build/dependency-cache" />
  <excludeFolder url="file://$MODULE_DIR$/build/incremental" />
  <excludeFolder url="file://$MODULE_DIR$/build/libs" />
  <excludeFolder url="file://$MODULE_DIR$/build/manifests" />
  <excludeFolder url="file://$MODULE_DIR$/build/res" />
  <excludeFolder url="file://$MODULE_DIR$/build/symbols" />
  <excludeFolder url="file://$MODULE_DIR$/build/tmp" />

在那之后,我重建了项目,R神奇地重新出现了。

我在可绘制资源中添加了一些图像,其中一个图像被命名为“super.jpg”,这是一个原因。

重命名图像并在此之后将项目与gradle文件同步修复了错误。

伙计们,我觉得这里有很多是瞎拍。在某些情况下,只有在解决了问题之后,“清洁和同步项目”才会有所帮助。

步骤1: 因此,去看看每个文件的顶部,其中包被指定如下:package ="YourURL.YourProject";并确保指定了正确的包(Your Own Project)。 你会在java文件和AndroidManifest.xml中发现这一点,对于java文件来说,引用正确的包是至关重要的,因为这个包包含了你所指向的资源(“R”)。如果他们不匹配,错误不能解决符号R发生。

步骤2: 清洁,同步,等等。完成

为什么这是随机发生的,或者我做错了什么?

如果复制和粘贴代码,应该密切注意上面解释的“package=”。更重要的是,当你粘贴代码时,它会立即通过某种调试器(请原谅我的糟糕技术术语)向你显示“假定错误”,它会立即考虑“错误的包”,你会得到所有的错误。 因此,即使您在粘贴后立即更正了符号,调试器也已经刷新。这就是为什么“清洁,同步,随便什么”有时管用

我有我的XML文件在一个布局文件夹,而不是菜单文件夹。

这是我们从Eclipse转移到Android Studio的结果。

解决方案对我来说很简单……将XML文件移动到MENU文件夹并重新编译。

在我的情况下:res/someLayout.xml文件出错,然后我解决它。 然后清除该项目。 错误消失了。