为每个Android版本使用不同的库模块

10

我希望为每种口味使用不同的库模块。

例如:

  • 免费口味 -> 我需要使用免费库模块
  • 付费口味 -> 我需要使用付费库模块

我的口味

productFlavors {
    free{
     ....... 
     }
    paid{
     ....... 
     }
   }

我尝试过什么

freeImplementation  project(path:':freeLib', configuration: 'free')//for free

paidImplementation  project(path:':paidLib', configuration: 'paid')//for paid

但我得到了编译错误,不能使用它。

注意:这不是重复的问题。我已经尝试了一些StackOverflow的问题,但它们已经过时了(它们正在使用compile)。

参考 - 基于Android Gradle中的多风格库的多风格应用程序

解决方案(来自Gabriele Mariotti的评论)

 freeImplementation project(path:':freeLib')
 paidImplementation project(path:':paidLib')
2个回答

21

如果您有一个包含多个产品风味的库,在您的 lib/build.gradle 文件中,您可以定义:

android {
    ...
    //flavorDimensions is mandatory with flavors.
    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"
        }
        paid{
            dimension "xxx"
        }
    }
    ...
}

在您的app/build.gradle中定义:

android {
    ...

    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"

            // App and library's flavor have the same name.
            // MatchingFallbacks can be omitted
            matchingFallbacks = ["free"]
        }
        paid{
            dimension "xxx"

            matchingFallbacks = ["paid"]
        }
    }
    ...
}
dependencies {
    implementation project(':mylib')
}

相反,如果你有单独的库可以在你的app/build.gradle中使用,那么你可以简单地这样做:

而是,如果你有单独的库可以在你的app/build.gradle中使用,那么你只需类似于以下代码:

dependencies {
    freeImplementation project(':freeLib')
    paidImplementation project(':paidLib')
}

谢谢回答。但是我想为每个口味使用单独的库,这可行吗? - Ranjithkumar
在这种情况下,如果你的库有产品风味,配置是相同的。否则只需使用 freeImplementation project(':mylib1') 和 paidImplementation。 - Gabriele Mariotti
2
是的,对我有效。谢谢回复。freeImplementation project(path:':freeLib') paidImplementation project(path:':paidLib') - Ranjithkumar
2
刚刚添加了我的最后一条评论到答案中,以支持两种情况。 - Gabriele Mariotti
matchingFallbacks挽救了我的一天。我本来可能要花一整天才能弄清楚那个部分。 - user882290
1
这是所有答案中最好的答案,它让我可以为应用程序和库设置相同的风格。我不需要从生成风格重新选择相同的风格。感谢您的回答。 :) - Chintan Rathod

5
  1. First add below gradle code snippet to your app/build.gradle

    flavorDimensions "env"
    productFlavors {
        dev {
            dimension "env"
        }
        pre {
            dimension "env"
        }
        prod {
            dimension "env"
        }
    }
    
  2. Second, add below gradle code snippet to your module/build.gradle

    flavorDimensions "env"
    productFlavors {
        register("dev")
        register("pre")
        register("prod")
    }
    
  3. Sync your project, and then you can find productFlavors were configured success,like below picture enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接