Android Studio 找不到从布局生成的 kotlinx 模块

Android Studio can't find kotlinx module generated from layout

我正在使用标准 Kotlin Android 扩展来引用布局 XML 中使用 kotlinx.android.synthetic.main.activity_main 中键入的 ID 定义的 View。我可以从 Android Studio 和 CLI 编译我的项目,所以这些引用似乎被正确解析;然而,在 Android Studio 中,导入语句显示为未解析,因此 none 类型的 ID 有效。

我的build.gradle如下:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-platform-android'
apply plugin: 'kotlin-android-extensions'

buildscript {
    ext.kotlin_version = '1.2.50'

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

androidExtensions {
    experimental = true
}

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 2
        versionName "0.3.0"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "org.jetbrains.anko:anko-sdk15:0.8.3"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:support-vector-drawable:27.1.1'
    implementation 'org.apache.commons:commons-io:1.3.2'
    expectedBy project(':engine')
    implementation project(':dialogue')
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.github.daniel-stoneuk:material-about-library:2.3.0'
}

我可以通过制作一个单独的 Android 库模块来解决这个问题,只包含特定于平台的位(重要的是,没有 kotlinx 使用),然后将其导入到主应用程序模块。这意味着主应用程序模块不再需要使用 kotlin-platform-android,而可以只使用 kotlin-android

总而言之,在包含平台特定位的模块中:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-platform-android'

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    expectedBy project(':engine')
}

在主模块中:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        freeCompilerArgs = ["-Xmulti-platform"]
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation project(':engine-android')
}

请注意,我们仍然需要将 -Xmulti-platform 传递给 Kotlin 编译器才能将 link 传递给 :engine-android;但我们使用的是 vanilla kotlin-android 插件,它似乎可以与 kotlin-android-extensions.

一起使用

请将以下代码添加到来自build.gradle的应用插件中:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}