LocaleKtx is a library to manage your application locale and language.
Works with "androidx.appcompat:appcompat:1.2.0"
Once you set a desired locale, LocaleKtx will enforce your application to provide correctly localized data via Resources class.
The setup is pretty simple:
- Using Dependency Injection (Koin Example)
-
Create library instance:
val appModule = module { single { createLocaleKtx(context = get()) } }
-
Setup Activity (nothing need to do in Fragments)
private val localeKtx: LocaleKtx by inject() override fun attachBaseContext(base: Context) { super.attachBaseContext(base) applyOverrideConfiguration(Configuration()) } override fun applyOverrideConfiguration(overrideConfiguration: Configuration) { val newConfig = localeKtx.wrapConfiguration(overrideConfiguration) super.applyOverrideConfiguration(newConfig) }
-
Change a locale
// Top level variable private val localeKtx: LocaleKtx by inject() fun changeLocale(locale: Locale){ localeKtx.setLocale(locale = locale) }
- Using Dependency Injection (Koin Example)
-
Initialize the library in Application.onCreate:
LocaleKtx.init(context)
-
Setup Activity (nothing need to do in Fragments)
override fun attachBaseContext(base: Context) { super.attachBaseContext(base) applyOverrideConfiguration(Configuration()) } override fun applyOverrideConfiguration(overrideConfiguration: Configuration) { val localeKtx = LocaleKtx.getInstance() val newConfig = localeKtx.wrapConfiguration(overrideConfiguration) super.applyOverrideConfiguration(newConfig) }
-
Change a locale
fun changeLocale(locale: Locale){ LocaleKtx.getInstance().setLocale(locale = locale) }
//Note: Activity will lose savedInstanceState
RecreateHelper.recreate(activity)
private val localeKtx: LocaleKtx by inject()
override fun attachBaseContext(base: Context) {
val newBase = localeKtx.wrapContext(baseContext = base)
super.attachBaseContext(newBase)
}
-
For keeping county and change only languge
setLocale(locale = Locale, keepCounty = true)
While using an app bundle, a user’s device only downloads string resources.
To keep languages in build.gradle set:
bundle {
language {
enableSplit = false
}
}
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation "com.github.jahongir28:localektx:1.0.0"
}
The MIT License (MIT)
Copyright 2021 Jahongir Bekmuhammetov
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.