Search code examples
androidandroid-gradle-pluginandroid-drawableandroid-build-type

Drawables not Found Under Custom Build Type


I have tried to configure a build type for my application that is identical with my release configuration except that it loads some sample data for testing the app. I performed the following steps:

I use the following buildTypes configuration in the app's build.gradle:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
    debug {
        applicationIdSuffix ".debug"
        versionNameSuffix "-debug"
    }
    sampledata {
        applicationIdSuffix ".sampledata"
        versionNameSuffix "-sampledata"
        signingConfig signingConfigs.config
    }
}

sourceSets {
    main { res.srcDirs = ['src/main/res', 'src/androidTest/res'] }
    sampledata { res.srcDirs = ['src/sampledata/res', 'src/main/res'] }
}

I created the corresponding source set (folder structure) under the src folder.

When I try to get a resource using the following statement the resource is not found (returning 0):

int resId = context.getResources().getIdentifier("someResource", "drawable", "com.myapp");

I had no trouble using the string resources in my source set but I'm not able to access the drawables in this configuration. Moving them to the drawable folder under main did not work either. What am I missing?


Solution

  • In order to access the resources in the source set the package name must match that of the build type, i.e. include the applicationIdSuffix. Change the getIdentifier() statement to

    int resId = context.getResources()
        .getIdentifier("someResource", "drawable", "com.myapp.sampledata");
    

    or

    int resId = context.getResources()
        .getIdentifier("someResource", "drawable", context.getPackageName());