search
LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

Organization

Android Flavor wrapper object

When using multiple flavors in a single Android project, a wrapper such as below is a useful utility when checking the current flavor (e.g. when assigning different features to different flavor).

It is not recommended to check the BuildConfig.Flavor string manually outside of this wrapper, due to potential errors in the string equality. Instead, we only need to ensure the "Name" enum in this wrapper is correct, to ensure correctness throughout the project.

The example here assumes two flavors in the build.gradle: "euro" and "japan"

object Flavor {

    // NOTE: must match flavor/dimension names given in build.gradle
    enum class Name {
        euro,
        asia
    }

    val current: Name 
    get() {
        Name.values().firstOrNull { it.name.equals(BuildConfig.FLAVOR) }?.let{ name->
            return name
        } ?: run {
            throw Exception("Unknown flavor: " + BuildConfig.FLAVOR)
        }
    }

    val isEuro: Boolean = current.equals(Name.euro)
    val isAsia: Boolean = current.equals(Name.asia)
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0