使用Kotlin编写的自定义插件中的访问gradle Android插件

问题描述 投票:0回答:1

我正在编写一个自定义的Gradle插件,该插件应该能够从Android插件访问配置参数。

我当然可以从groovy插件(这是我当前的代码)中做到这一点:

MyPlugin.groovy:

class MyPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.android.applicationVariants.all { variant ->
              variant.registerJavaGeneratingTask( // all the right parameters

我的问题是,我不希望插件位于Groovy中,我希望使用Kotlin。据我了解,我只需要在Kotlin中键入project.android无效,就需要编写类似于下面的内容:

MyPlugin.kt

import com.android.build.gradle.AndroidBasePlugin

class MyPlugin : Plugin<Project> {
    override fun apply(target: Project) {
         val android = target.plugins.findPlugin(AndroidBasePlugin::class.java)
          // and call android here

我的主要问题是导入import com.android.不存在。我尝试在build.gradle.kts上添加很多不同的依赖项,例如示例implementation("com.android.tools.build:gradle:3.6.1"),但没有任何东西可以使我对其进行访问。

问题:

  1. 这是正确的方法吗?

案例:(是)2.如何导入和使用它?(否)2.什么是正确的方法?

tl; dr:

如何在Gradle Kotlin插件中写入project.android.applicationVariants.all { variant ->

android gradle groovy gradle-plugin gradle-kotlin-dsl
1个回答
0
投票

您需要的是这样的东西:

        project.extensions.configure<AppExtension>("android") {
            it.applicationVariants.all {
                it.registerJavaGeneratingTask( // all the right parameters
            }
        }

并且您将需要com.android.tools.build:gradle依赖项。

为什么不被识别,我不确定...您在编写独立插件吗?如果是这样,那么您的工作原理就可以了...如果它是buildSrc文件夹中的嵌入式插件,那么您需要将lib添加到buildSrc build

© www.soinside.com 2019 - 2024. All rights reserved.