Kotlin files not able to use R.java

假装没事ソ 提交于 2019-12-10 14:19:40

问题


I created a new layout file in the appropriate resource folder. After syncing, when I try to reference the layout file, i.e. R.layout.activity_test, R is an "unresolved symbol". When I try to build in AS it fails.

The interesting thing is that if I manually import the R file and use it in code, when I try to build on command line, it works. The other thing is when I try to access the layout file using R in a Java file, that also works. So I know R.java is being generated.

I tried creating a totally new project, and R is accessible in Kotlin files.

What is the problem here?

Things I have tried:

  • Cleaned then built

  • Invalidated Caches / Restart

  • Blow away .gradle folders and recreate indexes

Other info:

  • AS v3.0.1

  • Tried both Kotlin v1.1.2-4 and v1.1.60

  • Gradle v4.2.1

  • Gradle Plugin v3.0.0


回答1:


Invalidate Caches/Restart worked for me.

Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
C:/Users/R3ZA/.gradle/caches/modules-2/files-2.1/me.eugeniomarletti.kotlin.metadata/kotlin-compiler-lite/1.0.3-k-1.2.40/a16e967c276379eaf6e1fa03af77664f003db947/kotlin-compiler-lite-1.0.3-k-1.2.40.jar (version 1.2)
C:/Users/R3ZA/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.3.20/eb2a232734e09fcd1b958a5c7520a93c6de38b32/kotlin-stdlib-1.3.20.jar (version 1.3)
C:/Users/R3ZA/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.3.20/7d7934e26ce34da1a0a8d00e38038d7cf3375e89/kotlin-stdlib-common-1.3.20.jar (version 1.3)



回答2:


Add the following under android section in your application module:

android {
  ...
  sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
  }
}

This lets Android Studio know that the kotlin directory is a source root, so when the project model is loaded into the IDE it will be properly recognized. Alternatively, you can put Kotlin classes in the Java source directory, typically located in src/main/java.


https://kotlinlang.org/docs/reference/using-gradle.html#android-studio




回答3:


If you have a warning in your project please fix it. in my case my Gradle version had a version Compile warning. the App runs fine but the R class was not recognized, so I change the gradle version and fix the warnings and all works well.



来源:https://stackoverflow.com/questions/47419597/kotlin-files-not-able-to-use-r-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!