Home > OS >  How can I share a constant in XML resource file and in source code as a static value
How can I share a constant in XML resource file and in source code as a static value

Time:12-31

I need the same constant in several places:

  • in the Android strings.xml XML resource file
  • in Kotlin source code as a static string (without access to a context)

How can I do?

I can see 3 possibilities, possible or not, but I don't see how to implement any of them:

a) Define the constant as resource in strings.xml, and import it in the source code.

XML: OK

<string name="my_constant">My.value</string>

Problem: I cannot define it as static / constant in my code, since I need a context to get its value, for ex. with context.getString(R.string.my_constant). Unless there is another way to do so, but I haven't found it.

Kotlin: ?

    companion object {
        const val MY_CONSTANT = ??.getString(R.string.my_constant)
    }

b) Define the consant in the Kotlin source code, and import its value in the XML resource file.

Kotlin: OK

    companion object {
        const val MY_CONSTANT = "My.value"
    }

Problem: I haven't found a way to import the value in strings.xml.

XML:?

<string name="my_constant" value="???"/>

c) Define the constant in build.gradle, import the value in both XML and Kotlin source code.

Problem: I just don't know how to do it, I've tried with BuildConfig but couldn't get the value in the source code.

gradle: ?

    buildTypes {
        all {
            // does not seem correct:
            buildConfigField 'String', 'MY_CONSTANT', '"My.value"'
        }
        release {
           // ... other settings
        }
    }

XML: ? Kotlin: ?

    companion object {
        const val MY_CONSTANT = BuildConfig.MY_CONSTANT // does not work
    }

CodePudding user response:

I usually define my API constants like this

define your constant in gradle.properties

API_KEY=""

then in your build.gradle(Module)

defaultConfig {

buildConfigField("String", "API_KEY", API_KEY)

}

now you should be able to call the constant from anywhere

BuildConfig.API_KEY
  • Related