Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle: adding assets folder dynamically

I have a project with many flavors, for each flavor I have a configuration file which specifies which assets to include.

here is what I have so far:

    applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def config = getFlavourConfig(variant.getFlavorName());
        if(config!=null) {
            if(config.get("font-assets") != null ) {
                config.get("font-assets").each {
                    println it
/*this is not working ->*/ variant.assets.srcDirs += ['src/extensions/assets/'+it]
                }
            }
        }
    }
}

getFlavourConfig parses a gson configuration file. The json has ["font-assets":["fontfolder1","fontfolder2"]

In this line

variant.assets.srcDirs += ['src/extensions/assets/'+it]

I want to add the assets dir to the flavor. Any ideas?

like image 665
Kamen Dobrev Avatar asked Jul 22 '16 15:07

Kamen Dobrev


2 Answers

You might be overthinking the work required. Just create the productFlavor then define the flavor's assets.srcDirs. Now we can sit back and let Android's gradle plugin do all the work.

android {
    //...
    productFlavors {
        blah {}
        more {}
    }
    sourceSets {
        blah {
            assets.srcDirs = files(getFlavorConfig(it.name))
        }
        more {
            assets.srcDirs = files(getFlavorConfig(it.name))
        }
    }
}

// simplified method for example
def getFlavorConfig(String str) {
    return ["$projectDir.absolutePath/src/extensions/assets/first", "$projectDir.absolutePath/src/extensions/assets/second"];
}

After the build our files will be where we expect:

$ ls app/build/intermediates/assets/blah/debug/
hello.txt world.txt

$ ls app/build/intermediates/assets/more/debug/
hello.txt world.txt

$ ls app/build/intermediates/assets/blah/release/
hello.txt world.txt

$ ls app/build/intermediates/assets/more/release/
hello.txt world.txt
like image 166
JBirdVegas Avatar answered Oct 07 '22 21:10

JBirdVegas


I ended up using one flavour at a build time and used the following line:

android.sourceSets.main.assets.srcDirs += ['src/extensions/assets/'+it]
like image 42
Kamen Dobrev Avatar answered Oct 07 '22 23:10

Kamen Dobrev