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.


当前回答

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

其他回答

“我也遇到过同样的问题,解决方法是:

1) Sync Project with gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project
4) File -> Invalidate caches

//imp step
5) Check your xml files properly.`

你们最近更新了SDK工具吗?启动android SDK管理器,确保你有最新的SDK工具,现在是独立于平台工具。当我第一次更新我的SDK管理器时,我也遇到了同样的问题,SDK构建工具包在安装/更新时没有出现,直到我关闭并重新打开SDK管理器。

在我的情况下,代码在我更新android studio之前正常工作。更新后未生成R文件。我正在处理一个自定义视图,并且有一个属性

<attr name="showText" format="boolean" />

在我的declare stylable中。同样的属性也被系统的ui使用:

<style name="Base.Widget.AppCompat.CompoundButton.Switch" parent="android:Widget.CompoundButton">
    <item name="track">@drawable/abc_switch_track_mtrl_alpha</item>
    <item name="android:thumb">@drawable/abc_switch_thumb_material</item>
    <item name="switchTextAppearance">@style/TextAppearance.AppCompat.Widget.Switch</item>
    <item name="android:background">?attr/selectableItemBackgroundBorderless</item>
    <item name="showText">false</item>// this line
</style>

我将之前的showText重命名为showTextFormat,然后gradle sync重新生成R.java文件。

我在androidmanifest中有android:textAllCaps = "false",这对R文件造成了严重破坏。我删除了,一切正常。我认为目标sdk设置得不够高。

我现在也有类似的问题。问题是在我的项目中,我有更多的模块。例如app模块和库模块。虽然类和R.string资源都来自app模块,但我在那里导入了com.package.library.R。不知怎的,Android Studio没有意识到这是一个错误,Gradle/Sync构建我的项目没有问题。但是当我试图运行单元测试时,Gradle构建失败,出现了所描述的错误。

package com.package.app

import com.package.library.R;
//...

class SomeClass {
  //...
  public void someMethod() {
     Toast.make(context, R.string.message, TOAST_LONG).show();
  }
}

当r .string. message资源实际上在我的com.packagename.app模块而不是com.packagename.library模块时。删除导入…解决了我的问题。