Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (4k points)

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. Just like a pre-processor macros in C/C++...

An example of a declaration would be something like that ... :

android {

    debug {

        A_VAR_RETRIEVABLE_IN_JAVA = 42

    }

    release {

        A_VAR_RETRIEVABLE_IN_JAVA = 42+52

    }

}

Is there a way to do something like that?

1 Answer

0 votes
by (46k points)

Create 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

Create Android resources

android {

    buildTypes {

        debug{

            resValue "string", "app_name", "My App Name Debug"

        }

        release {

            resValue "string", "app_name", "My App Name"

        }

    }

}

You can reach them in the normal procedure with @string/app_name or R.string.app_name

Related questions

0 votes
1 answer
asked Sep 18, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...