Home > Mobile >  Custom strings file
Custom strings file

Time:12-02

I'm wondering if there is a way to force getting strings from the custom file? Let's say I would like to have testing strings set and use them in the debug mode. As far as I know, there is no possibility to create a custom Locale and use for example values-test folder. But maybe there is the possibility to override something and force getting strings from the assets folder file?

CodePudding user response:

If you want to separate string resources between release and debug - just separate them in folders (check this answer):

project
  -app
    -src
      -debug
        -java
          ...
        -res
          -values
            -strings.xml
      -release
        -java
          ...
        -res
          -values
            -strings.xml
      -main
        -java
          ...
        -res
          -values
            -strings.xml

But if you want to override string resources there is great and useful library Restring.

You can put your own string resources to it and it will replace your default ones. Successfully used in project with 10M installs.

CodePudding user response:

You can do that in build.gradle(app) by using following snipped of code.

android {
    buildTypes {
        debug {
            resValue 'string', 'api_key', '"000000000"'
        }
        release {
            resValue 'string', 'api_key', '"123456789"'
        }
    }
}

Usage (Java)

val text = resources.getString(R.string.api_key)
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()

Usage (Kotlin)

String text = resources.getString(R.string.api_key)
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()

Add this, sync your project & build your project. You may seem red warning, ignore that and use it.

No need to manually check for BuildConfigs.

  • Related