Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@passsy
Last active February 9, 2022 13:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passsy/99b2bbc6a1d84a680835b6ba9a9f2741 to your computer and use it in GitHub Desktop.
Save passsy/99b2bbc6a1d84a680835b6ba9a9f2741 to your computer and use it in GitHub Desktop.
Allows easy iteration about all available locales. Kotlin Collection implementation for LocaleList which doesn't implement Collection<Locale> itself.
package com.pascalwelsch.android.util
import android.content.Context
import androidx.core.os.ConfigurationCompat
import androidx.core.os.LocaleListCompat
import java.util.Locale
/**
* Returns an [Iterable] for the languages of the user, sorted by priority. First choice first.
*/
fun Context.userLocales(): Iterable<Locale> {
return ConfigurationCompat.getLocales(resources.configuration).asIterable()
}
fun LocaleListCompat.asIterable(): Iterable<Locale> = LocaleIterable(this)
private class LocaleIterable(private val localList: LocaleListCompat) : Iterable<Locale> {
override fun iterator(): Iterator<Locale> = LocaleIterator(localList)
}
private class LocaleIterator(private val localList: LocaleListCompat) : Iterator<Locale> {
var i = -1
override fun hasNext(): Boolean = (i + 1) < localList.size()
override fun next(): Locale {
if (!hasNext()) throw NoSuchElementException()
i++
return localList.get(i)
}
}
@passsy
Copy link
Author

passsy commented Oct 24, 2017

Usage:

fun userSpeaksGerman(): Boolean {
    val germanLocale = context!!.userLocales()
            .firstOrNull { it.language == "de" }
    return germanLocale != null
}

@tobltobs
Copy link

tobltobs commented Nov 8, 2019

I guess

override fun hasNext(): Boolean = localList.size() < (i + 1)

should be

override fun hasNext(): Boolean = localList.size() > (i + 1)

@passsy
Copy link
Author

passsy commented Nov 9, 2019

Thanks @tobltobs, I updated it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment