Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...