Is it possible to declare a variable in Gradle usable in Java?

后端 未结 9 1218
春和景丽
春和景丽 2020-11-22 09:11

Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:26

    Here are two ways to pass value from Gradle to use in Java;

    Generate Java Constants

    android {
        buildTypes {
            debug {
                buildConfigField "int", "FOO", "42"
                buildConfigField "String", "FOO_STRING", "\"foo\""
                buildConfigField "boolean", "LOG", "true"
            }
    
            release {
                buildConfigField "int", "FOO", "52"
                buildConfigField "String", "FOO_STRING", "\"bar\""
                buildConfigField "boolean", "LOG", "false"
            }
        }
    }
    

    You can access them with BuildConfig.FOO

    Generate Android resources

    android {
        buildTypes {
            debug{
                resValue "string", "app_name", "My App Name Debug"
            }
            release {
                resValue "string", "app_name", "My App Name"
            }
        }
    }
    

    You can access them in the usual way with @string/app_name or R.string.app_name

提交回复
热议问题