Java Android Studio 3.1.3 - 未解决的参考:R - Kotlin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51621301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:10:34  来源:igfitidea点击:

Android Studio 3.1.3 - Unresolved reference: R - Kotlin

javaandroidandroid-studiogradlekotlin

提问by Tamim Attafi

I am new to kotlin, i have converted some code from java but it seems like there's something wrong, The R in findViewById(R.id.my_id) is highlighted in red and it shows this message : "Unresolved reference: R".. I've been looking for a solution but i seem not to figure it out, So what should i do? Here's a screenshot :

我是 kotlin 的新手,我已经从 Java 转换了一些代码,但似乎有问题,findViewById(R.id.my_id) 中的 R 以红色突出显示,并显示以下消息:“未解析的引用:R”..我一直在寻找解决方案,但我似乎没有弄清楚,那我该怎么办?这是一个屏幕截图:

enter image description here

在此处输入图片说明

采纳答案by Tamim Attafi

The issue can be caused by many factors,

这个问题可能是由很多因素引起的,

  • as mentioned by martomstom in this Answerthe issue is sometimes caused by com.android.tools.build:gradleversion, changing it's version to a more stable one would solve the problem: for example: com.android.tools.build:gradle:3.4.0-alpha02with com.android.tools.build:gradle:3.2.1
  • Also, having libraries from the same group, but with different versions may cause the problem or even more runtime errors. use the exclude group method like the following : implementation('com.squareup.picasso:picasso:2.71828') { exclude(group: 'com.android.support') }in this case, picasso library uses android.support components, the android library version used in picasso is different than the one you're currently using in your app, so in order to solve this issue, we have to exclude it completely from its sub library and class groups.

  • It can also happen by the mismatch of resources and code, including this importation line in your activity may solve the problem too : import com.package.name.R

  • Sometimes it can happen because of the IDE, performances or memory.. Cleaning the project from time to time may save you some time, on Android Studio it would be something like this : Build -> Clean Project / Rebuild Project-Cleaning IDE cash also helps with performance and memory, on Android Studio it would look like this : File-> Invalidate Chases/ Restart -> Invalidate Cashes and Restart
  • I noticed that this problem happens to me the most of the time when importing new resources, Using prohibited characters in their names would fire the error, such as . , , - , UpperCase or special Letters
  • And as a suggestion , if you're using Kotlin, i really recommend using Kotlin extensions in your activity such as : import kotlinx.android.synthetic.main.activity_page.*or if you're using a custom view : kotlinx.android.synthetic.main.view_layout.view.*after that, in onCreat() method of an activity , you'll only have to call the id, for example : my_edit_text_ID.text = "Kotlin Dbest!", or from a custom view : mCostumView.my_edit_text_ID.text = "Kotlin Dbest!"
  • 由martomstom在此提到的回答这个问题有时是造成com.android.tools.build:gradle版本,更改它的版本更稳定的一个可以解决这个问题:例如:com.android.tools.build:gradle:3.4.0-alpha02com.android.tools.build:gradle:3.2.1
  • 此外,具有来自同一组但具有不同版本的库可能会导致问题甚至更多运行时错误。使用像下面这样的 exclude group 方法:implementation('com.squareup.picasso:picasso:2.71828') { exclude(group: 'com.android.support') }在这种情况下,picasso 库使用 android.support 组件,picasso 中使用的 android 库版本与您当前在应用程序中使用的版本不同,因此为了解决此问题,我们必须从它的子库和类组中完全排除它。

  • 资源和代码不匹配也可能发生这种情况,在您的活动中包含此输入行也可以解决问题: import com.package.name.R

  • 有时它可能因为 IDE、性能或内存而发生。不时清理项目可能会节省你一些时间,在 Android Studio 上它会是这样的:Build -> Clean Project / Rebuild Project-在 Android 上清理 IDE 现金也有助于性能和内存工作室它看起来像这样:File-> Invalidate Chases/ Restart -> Invalidate Cashes and Restart
  • 我注意到这个问题在导入新资源的大部分时间发生在我身上,在他们的名字中使用禁止的字符会触发错误,例如 . , , - , UpperCase or special Letters
  • 作为建议,如果您使用Kotlin,我真的建议您在您的活动中使用 Kotlin 扩展,例如:导入kotlinx.android.synthetic.main.activity_page.*或者如果您使用自定义视图:kotlinx.android.synthetic.main.view_layout.view.*之后,在活动的 onCreat() 方法中,您将只需要调用 id,例如 : my_edit_text_ID.text = "Kotlin Dbest!",或从自定义视图中调用:mCostumView.my_edit_text_ID.text = "Kotlin Dbest!"

EDIT :

编辑 :

  • I have faced this issue againe and the problem was the '' R '' library was imported from 2 different sources :

    com.android.R

    com.example.package.R

    You must only import the '' R '' library with your application package name, in this case com.example.package.RSometimes the library is not imported at all, to import it, click on the unresolved reference Rand press Alt + Enter

  • 我再次遇到了这个问题,问题是“R”库是从 2 个不同来源导入的:

    com.android.R

    com.example.package.R

    您必须只导入带有您的应用程序包名称的 '' R '' 库,在这种情况下,com.example.package.R有时根本没有导入该库,要导入它,请单击未解析的引用R并按Alt + Enter

EDIT:

编辑:

As tobltobsmentioned in the comments section: " Most of the time the problem is caused by another error which prevents the build system from creating generated sources. To find the root cause look at the gradle log (the "toggle view" icon below of the green hammer in the Build output) and look for errors unrelated to R or BuildConfig (also generated). If there is no other error left and the problem with R persists then maybe something of this list might help. "

正如评论部分中提到的tobltobs:“大多数情况下,问题是由另一个错误引起的,该错误阻止构建系统创建生成的源。要找到根本原因,请查看 gradle 日志(下面的“切换视图”图标Build 输出中的绿色锤子)并查找与 R 或 BuildConfig 无关的错误(也生成)。如果没有其他错误并且 R 的问题仍然存在,那么此列表中的某些内容可能会有所帮助。“

回答by Earl Whitney

This worked for me. How much work it is depends on how big your project is. I started a new project, created the required modules (XML, Kotlin, colors, strings, etc.), then copied the code into the modules in the new project from the modules in the old project. Copying XML saves a lot of time compared to recreating the UI. All in all, it take a little while, but I have spent much more time tring to fix the unresolved reference error without it.

这对我有用。多少工作取决于你的项目有多大。我开始了一个新项目,创建了所需的模块(XML、Kotlin、颜色、字符串等),然后将代码从旧项目中的模块复制到新项目中的模块中。与重新创建 UI 相比,复制 XML 可以节省大量时间。总而言之,这需要一点时间,但我花了更多的时间来修复没有它的未解决的参考错误。

回答by Fireworks

Use gradle commands.
In Android Studio, on the right menu:
Gradle -> :app -> Tasks -> build -> clean.
After that, Gradle -> :app -> Tasks -> build -> build

使用 gradle 命令。
在 Android Studio 中,在右侧菜单上:
Gradle -> :app -> Tasks -> build -> clean.
在那之后,Gradle -> :app -> Tasks -> build -> build

回答by martomstom

I used com.android.tools.build:gradle:3.3.0-alpha13 and had the same issue. Changing to stable Version 3.2.1 solved this problem for me.

我使用了 com.android.tools.build:gradle:3.3.0-alpha13 并遇到了同样的问题。更改为稳定版本 3.2.1 为我解决了这个问题。

回答by PRANAY REDDY

TRY THIS

尝试这个

Go to the content_main.xml file and there you need to change the

转到 content_main.xml 文件,在那里您需要更改

android:id="@+id/??????">line of code to whatever id you have given to your file.

android:id="@+id/??????">代码行到您提供给文件的任何 id。

Replace question mark ??????with the related file id name.(IF you dont know the id go to the design tab on the bottom and click on the related Asset.

??????相关文件 id 名称替换问号。(如果您不知道 id,请转到底部的设计选项卡并单击相关资产。

On the right side below attributes, you can find the ID you have given to it. If it is blank you can freshly name it and Android Studio will write the code.

在属性下方的右侧,您可以找到为其提供的 ID。如果它是空白的,您可以重新命名它,Android Studio 将编写代码。

Then restart Android Studio. Hope this will help. Happy coding.

然后重启Android Studio。希望这会有所帮助。快乐编码。

回答by Sam

So this is a misleading error.

所以这是一个误导性的错误。

I'm going to explain the 30,000 foot view of what is happening. This is not EXACT order or EXACT flow, it is just pretty damn close ;) so if you know more then I do of the exact order and care to make corrections with links, feel free I won't stop ya :).

我将解释正在发生的事情的 30,000 英尺视图。这不是确切的顺序或确切的流程,它只是非常接近 ;) 所以如果你知道更多,那么我会做确切的顺序并注意对链接进行更正,请随意我不会阻止你 :)。

The Process

过程

The R file is generated code.

There is an order to the generation.

Gradle will do it's magic, pull it's dependencies and kick off it's warning and error tree first,

then Android converts all Kotlin to Java behind the scenes. Yup that's right, our beloved Kotlin still has to be Java to compile for our beloved ART virtual machine.

Then it runs through and does the adapters that you have created for JVM Statics and a few other tasks. Next up it compiles all the xml databinding files first to create the generated databinding files.

If everything succeeds it moves on to processing the assets and resources. Which creates pointers or IDs for each resource that you reference in code. Next it will run through and begin compiling the code and packaging process after that.

R 文件是生成的代码。

世代有秩序。

Gradle 会发挥它的魔力,拉取它的依赖项并首先启动它的警告和错误树,

然后 Android 在幕后将所有 Kotlin 转换为 Java。是的,没错,我们心爱的 Kotlin 仍然必须是 Java 才能为我们心爱的 ART 虚拟机编译。

然后它运行并执行您为 JVM 静态和一些其他任务创建的适配器。接下来,它首先编译所有 xml 数据绑定文件以创建生成的数据绑定文件。

如果一切顺利,它将继续处理资产和资源。它为您在代码中引用的每个资源创建指针或 ID。接下来它将运行并开始编译代码和打包过程。

Pretty straight forward process, but here in lies the problem.

非常直接的过程,但问题就在这里。

The misleading Error

误导性错误

If any step fails before the R generation is complete, then the R does not get generated. Sometimes a simple rebuild is all you need to do, sometimes a simple File->Invalidate Cache and Restart is all you need. However, more often than not you have a code issue in your gradle, your xml, your databinding or your adapters that are preventing the compiler from even reaching the R generation stage.

如果在 R 生成完成之前任何步骤失败,则不会生成 R。有时只需简单的重建即可,有时只需简单的 File->Invalidate Cache and Restart 即可。但是,通常情况下,您的 gradle、xml、数据绑定或适配器中的代码问题会阻止编译器甚至到达 R 生成阶段。

So the next question is

所以下一个问题是

"Well shoot, how do we troubleshoot it if the errors are worthless or non-existent".

“好吧,如果错误毫无价值或不存在,我们如何解决它”。

Well first let's talk about the many ways these errors present themselves.

那么首先让我们谈谈这些错误的多种表现方式。

  • Duplicate Databinding class found
  • xml Binding Error at line #
  • Couldn't find matching signature of bind:customAdapterMethod
  • Can't find R file of the correct project, only shows import options for sub modules or incorrect namespace R files.
  • Couldn't find DataBindingUtility or DataBinding for activity/fragment
  • And many other various ways as well, too many to list them all
  • 发现重复的数据绑定类
  • 第 # 行的 xml 绑定错误
  • 找不到 bind:customAdapterMethod 的匹配签名
  • 找不到正确项目的 R 文件,只显示子模块的导入选项或不正确的命名空间 R 文件。
  • 找不到活动/片段的 DataBindingUtility 或 DataBinding
  • 还有许多其他各种方式,太多了,无法一一列举

Next, let's talk about potential candidates causing the problem. As there are sooo many lol.

接下来,让我们谈谈导致问题的潜在候选人。因为有很多哈哈。

  • Gradle Syncing issues
  • Caching Issues (File->Restart and Invalidate Cache)
  • xml elements with wrong namespace
  • xml elements with bad IDs or references IDs out of order (i.e. you say align to right of an element that is lower in the xml document then the sibling element that is trying to reference it)
  • xml data binding issues referencing namespace or member that doesn't exist or is not typed correctly
  • xml data binding issues in non-auto-filled spots like custom attributes using adapters as those are harder to spot. i.e. bind:myCustomMethod=@"myObject.mistypedProperty()"
  • JVM Static adapters with issues or duplicated signatures
  • Duplicated or bad character in the Strings or Dimens file or any other xml file for that matter
  • Private variable marked for @Binding without properties to access it
  • Member variable marked for @Binding that matches a parent class method causing duplications that manifests itself in almost impossible errors
  • Mismatch of types like using an adapter that takes (Int) but you are passing (Int?) via data binding and it isn't recognized with JVM Statics until compile time
  • You selected IMPORT on a popup to import R file of a sub module instead of the application file
  • Having bindable members in a child or parent class, but not giving fully qualified namespace to class cast in the XML usage of the parent or child class. As the databinding compiler is not smart enough to realize the variable provided for class Foo is also parentFoo baseclass, so you have to qualify it as android:text="@((com.path.parentFoo)foo).parentMethod"
  • Having a method name in a class, that matches a "generated property from @Binding member variable" i.e. firstName as a variable, but then having a method called getFirstName in a parent or child class, because you are now matching a method name that will get auto generated, thus causing dataBindingUtility duplication class errors.
  • There are more causes, but this should give you a series of places to look, but the list can go on and on seriously.
  • Gradle 同步问题
  • 缓存问题(文件-> 重新启动并使缓存无效)
  • 具有错误命名空间的 xml 元素
  • 具有错误 ID 或引用 ID 乱序的 xml 元素(即,您说对齐到 xml 文档中较低的元素的右侧,然后是尝试引用它的同级元素)
  • xml 数据绑定问题引用不存在或未正确键入的命名空间或成员
  • xml 数据绑定问题在非自动填充的地方,比如使用适配器的自定义属性,因为这些问题更难发现。即绑定:myCustomMethod =@“myObject.mistypedProperty()”
  • 有问题或重复签名的 JVM 静态适配器
  • Strings 或 Dimens 文件或任何其他与此相关的 xml 文件中的重复或错误字符
  • 为@Binding 标记的私有变量没有访问它的属性
  • 标记为@Binding 的成员变量与父类方法匹配,导致重复,几乎不可能出现错误
  • 类型不匹配,例如使用采用 (Int) 的适配器,但您通过数据绑定传递 (Int?),并且直到编译时才被 JVM 静态识别
  • 您在弹出窗口中选择了 IMPORT 以导入子模块的 R 文件而不是应用程序文件
  • 在子类或父类中具有可绑定成员,但没有为在父类或子类的 XML 用法中强制转换的类提供完全限定的命名空间。由于数据绑定编译器不够聪明,无法实现为类 Foo 提供的变量也是 parentFoo 基类,因此您必须将其限定为 android:text="@((com.path.parentFoo)foo).parentMethod"
  • 在类中有一个方法名称,它匹配“从@Binding 成员变量生成的属性”,即作为变量的 firstName,但是在父类或子类中有一个名为 getFirstName 的方法,因为您现在正在匹配一个方法名称,它将get 自动生成,从而导致 dataBindingUtility 重复类错误。
  • 有更多的原因,但这应该给你一系列的地方去看看,但这个清单可以继续认真地继续下去。

Unfortunately this happens a lot in bleeding edge technologies where the UI tools are not up to speed with the terminal based tools yet. So I suggest you run from the project root in a terminal with

不幸的是,这种情况在前沿技术中经常发生,其中 UI 工具还没有跟上基于终端的工具的速度。所以我建议你从终端中的项目根目录运行

bash gradlew assembleRelease --debug

When it fails, and it will. Start scrolling up through the logs until you find the red where you see what is actually failing and preventing the next stage from occurring.

当它失败时,它会。开始向上滚动日志,直到找到红色,您可以看到实际失败并阻止下一阶段发生的地方。

You will find this especially useful when you start dealing with databinding.

当您开始处理数据绑定时,您会发现这特别有用。

TIP:

提示:

When you start dealing with databinding, make sure you compile and run often because the goal is to recognize right away before doing other files to make sure you didn't break generation and make your life MUCH easier to know code you just added caused the issue before getting too far.

当您开始处理数据绑定时,请确保经常编译和运行,因为目标是在执行其他文件之前立即识别以确保您没有中断生成并使您的生活更容易了解您刚刚添加的代码导致问题在走得太远之前。

Times to compile and run to confirm no issues before moving on.

在继续之前编译和运行以确认没有问题的时间。

  • If you add a few JVM statics compile and run
  • If you add variables to your XML to use
  • If you bind to properties of your model in 1 file
  • If you add a binding to a JVMStatic
  • If you add bindable members or properties to an model
  • If you refactor moving observable member variables or properties into children or base classes
  • Any other xml or binding related elements that can effect the generated code.
  • 如果添加一些JVM静态编译并运行
  • 如果您向 XML 添加变量以使用
  • 如果您绑定到 1 个文件中的模型属性
  • 如果向 JVMStatic 添加绑定
  • 如果向模型添加可绑定成员或属性
  • 如果您将可观察的成员变量或属性重构为子类或基类
  • 可以影响生成的代码的任何其他 xml 或绑定相关元素。

Like I mentioned above, the reason is to avoid getting so many changes, that it becomes a troubleshooting nightmare to find a generic vague, horrible error related to generated databinding code. I'm sure the tools will improve, but for now, do yourself a favor and compile and run often when changing Databinding related items.

就像我上面提到的,原因是为了避免进行如此多的更改,以至于找到与生成的数据绑定代码相关的通用模糊、可怕的错误成为故障排除的噩梦。我确信这些工具会改进,但现在,请帮自己一个忙,在更改数据绑定相关项目时经常编译和运行。

Happy Coding

快乐编码

回答by Kenneth Argo

I believe that I came across the real answer (though by accident).

我相信我遇到了真正的答案(尽管是偶然的)。

I also, as the OP had my KT file fail to location R. as well as other classes that happen to be in java. What I noticed was that there was a case difference I the filenames. Once I corrected the import statements to match the case of the package (aka, folder) the errors resolved.

我也是,因为 OP 让我的 KT 文件无法定位 R. 以及碰巧在 java 中的其他类。我注意到文件名存在大小写差异。一旦我更正了导入语句以匹配包(又名,文件夹)的情况,错误就解决了。

回答by Josue

I had the same problem with R reference too. Finally Android Studio 3.3 has been released and using 'com.android.tools.build:gradle:3.3.0'the problem has been fixed!

我对 R 参考也有同样的问题。Android Studio 3.3 终于发布了,使用'com.android.tools.build:gradle:3.3.0'问题已经解决!

回答by HasBert

I had the same problem, and I tried not to downgrade from gradle version 3.3 to gradle version 3.2.1. Instead I updated Android Studio to version 3.3, which made the trick for me ;-)

我遇到了同样的问题,我尝试不从 gradle 3.3 版降级到 gradle 3.2.1 版。相反,我将 Android Studio 更新到了 3.3 版,这对我来说是个技巧;-)

回答by dudukee

I update Android Studio to version 3.3.1 and solved this problem.

我将 Android Studio 更新到 3.3.1 版并解决了这个问题。