Using locale settings to detect wheter to use imperial units

前端 未结 6 570
被撕碎了的回忆
被撕碎了的回忆 2021-01-31 09:00

I\'m working on an app that wants to display lengths either in centimeters (cm) or in inches(\"). Is there a way to select the right unit from the locale? In any event I\'m also

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 09:32

    Building on the other nice solutions here, you can also implement this as a Kotlin extension function to the Locale object:

    fun Locale.isMetric(): Boolean {
        return when (country.toUpperCase(this)) {
            "US", "LR", "MM" -> false
            else -> true
        }
    }
    

    This way, all you need to do is call:

    val metric = Locale.getDefault().isMetric()
    

提交回复
热议问题