How to get a resource value in build.gradle?

前端 未结 3 1574
走了就别回头了
走了就别回头了 2020-12-14 07:59

The resValue method (or whatever it\'s called) allows you to set a resource value in buildTypes or productFlavors. I

相关标签:
3条回答
  • 2020-12-14 08:03

    You can check the build variants like this

    Define values in gradle

    buildTypes {
        debug{
            buildConfigField "String", "Your_string_key", '"yourkeyvalue"'
            buildConfigField "String", "SOCKET_URL", '"some text"'
            buildConfigField "Boolean", "LOG", 'true'
        }
        release {
            buildConfigField "String", "Your_string_key", '"release text"'
            buildConfigField "String", "SOCKET_URL", '"release text"'
            buildConfigField "Boolean", "LOG", 'false'
    
        }
    }
    

    And to access those values using build variants:

     if(!BuildConfig.LOG)
          // do something with the boolean value
    

    Or

    view.setText(BuildConfig.yourkeyvalue);
    
    0 讨论(0)
  • 2020-12-14 08:17

    To have an alternative version of a resource in debug builds you can use the debug source set.

    strings.xml can be found under following path src/main/res/values, which means it's in the main source set. If you create a new directory src/debug/res/values you can put a new strings.xml file in there with values that should be overridden in debug builds. For example:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="app_name">My Application Debug</string>
    </resources>
    

    This will replace whatever value app_name has in your main file. You don't have to duplicate all the strings in here - ones you don't include here are simply taken from the main file.

    0 讨论(0)
  • 2020-12-14 08:25

    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

    0 讨论(0)
提交回复
热议问题