Last active
February 9, 2022 13:05
Allows easy iteration about all available locales. Kotlin Collection implementation for LocaleList which doesn't implement Collection<Locale> itself.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @tobltobs, I updated it