Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

android - How to get a resource value in build.gradle?

The resValue method (or whatever it's called) allows you to set a resource value in buildTypes or productFlavors. Is there a corresponding way to get a resource value that was set by resValue?

It appears that productFlavors is evaluated before buildTypes, so a resValue set in buildTypes takes precedence. I want to append "Debug" to the app name in debug builds, but I need to get the value that was set in the product flavor in order to append to it.

Edit: I tried Marcin Koziński's suggestion to use a variable, but all product flavors are evaluated before any build type. Therefore, this does not work:

android {
    String appName = ""

    productFlavors {
        Foo {
            appName = "Foo"
        }

        Bar {
            appName = "Bar"
        }
    }

    buildTypes {
        release {
            resValue "string", "app_name", appName 
        }

        debug {
            resValue "string", "app_name", appName + " Debug"
        }
    }
}

In buildTypes, appName always has the value from the last product flavor. So in this example, all builds receive the name "Bar" or "Bar Debug".

Basically, I need a resValueSuffix analogous to applicationIdSuffix. Apparently no such animal exists. Does the com.android.application plugin expose anything that I could use to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are only trying to set the App Label (or other manifest values) you can solve this with manifest placeholders.

android {

    productFlavors {
        Foo {
             applicationId "com.myexample.foo"
             manifestPlaceholders.appName = "Foo"
        }

        Bar {
             applicationId "com.myexample.bar"
             manifestPlaceholders.appName = "Bar"
        }
    }

    buildTypes {
        release {
            manifestPlaceholders.appNameSuffix =""
        }

        debug {
            manifestPlaceholders.appNameSuffix =".Debug"
            applicationIdSuffix ".debug"
        }
    }
}

Then in your Android Manifest you simply use both placeholders for your app name (or other values)

 <application
        android:label="${appName}${appNameSuffix}"
        ...
 </application>

This allow you to install all 4 variants side by side on a single device as well as give them different names in the app drawer / launcher.

EDIT 11/22/2019

Updated how placeholders values are set based on feedback from @javaxian


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...