Skip to content

Instantly share code, notes, and snippets.

@passsy

passsy/Locale.kt

Last active May 28, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@passsy passsy commented Oct 24, 2017

Usage:

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

This comment has been minimized.

Copy link

@tobltobs 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

This comment has been minimized.

Copy link
Owner Author

@passsy 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