• This repository has been archived on 22/Jun/2022
  • Stars
    star
    979
  • Rank 44,836 (Top 1.0 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Android] In-app language changing library

Android Arsenal Maven Central Minimum SDK Version Workflow Status

Discontinued

Since Google announced Android 13 with per-app language preferences supports. This feature also backport to older Android version with AndroidX. So there's no reason to contribute this library anymore. For more stability, compatibility, and longer supports from Google team, please migrate to AndroidX. See Migrate to AndroidX guide.

Localization Library

Header image Android library for in-app language changes support in your application

Feature

  • In-app language changing
  • Default language when first launch
  • Work with string resource in XML and programmatically
  • RTL language support
  • Align on platform behavior

Demo

Try it at Google Play

Download

Since version 1.2.9 will move from JCenter to MavenCentral

// build.gradle (project)
allprojects {
    repositories {
        mavenCentral()
        /* ... */
    }
}

Gradle

implementation 'com.akexorcist:localization:1.2.11'

(Optional) You can exclude androidx.appcompat:appcompat, if your project does not use AppCompat.

implementation ('com.akexorcist:localization:1.2.11') {
    exclude group: 'androidx.core', module: 'core'
}

Usage

Custom application class which extends from LocalizationApplication is require.

class MainApplication: LocalizationApplication() {
    /* ... */
    override fun getDefaultLanguage(context: Context) = Locale.ENGLISH
}

Either not, using LocalizationApplicationDelegate with additional code as below

class MainApplication: Application() {
    private val localizationDelegate = LocalizationApplicationDelegate()
    
    override fun attachBaseContext(base: Context) {
        localizationDelegate.setDefaultLanguage(base, Locale.ENGLISH)
        super.attachBaseContext(localizationDelegate.attachBaseContext(base))
    }
    
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        localizationDelegate.onConfigurationChanged(this)
    }
    
    override fun getApplicationContext(): Context {
        return localizationDelegate.getApplicationContext(super.getApplicationContext())
    }
    
    override fun getResources(): Resources {
        return localizationDelegate.getResources(baseContext, super.getResources())
    }
}

For the activities, extends from LocalizationActivity.

class MainActivity: LocalizationActivity() {
    /* ... */
}

Or using LocalizationActivityDelegate with additional code

open class CustomActivity : Activity(), OnLocaleChangedListener {
    private val localizationDelegate = LocalizationActivityDelegate(this)

    public override fun onCreate(savedInstanceState: Bundle?) {
        localizationDelegate.addOnLocaleChangedListener(this)
        localizationDelegate.onCreate()
        super.onCreate(savedInstanceState)
    }

    public override fun onResume() {
        super.onResume()
        localizationDelegate.onResume(this)
    }

    override fun attachBaseContext(newBase: Context) {
        applyOverrideConfiguration(localizationDelegate.updateConfigurationLocale(newBase))
        super.attachBaseContext(newBase)
    }

    override fun getApplicationContext(): Context {
        return localizationDelegate.getApplicationContext(super.getApplicationContext())
    }

    override fun getResources(): Resources {
        return localizationDelegate.getResources(super.getResources())
    }

    fun setLanguage(language: String?) {
        localizationDelegate.setLanguage(this, language!!)
    }

    fun setLanguage(locale: Locale?) {
        localizationDelegate.setLanguage(this, locale!!)
    }

    val currentLanguage: Locale
        get() = localizationDelegate.getLanguage(this)

    // Just override method locale change event
    override fun onBeforeLocaleChanged() {}
    override fun onAfterLocaleChanged() {}
}

Then prepare your multilingual content in string resource.

Multilingual Content

Public method on LocalizationActivity

It have only 4 public methods.

fun setLanguage(language: String)
fun setLanguage(language: String, country: Strinng)
fun setLanguage(locale: Locale)
fun getCurrentLanguage(): String

setLanguage Set the language that you need to change.

For example

setLanguage("th")                             // Language : Thailand
setLanguage("th", "TH")                       // Language : Thailand, Country : Thai
setLanguage(Locale("th", "TH"))               // Language : Thailand, Country : Thai
setLanguage("en")                             // Language : English
setLanguage("en", "GB")                       // Language : English,  Country : Great Britain
setLanguage("en", "US")                       // Language : English,  Country : United States
setLanguage(Locale("en", "US"))               // Language : English,  Country : United States
setLanguage(Locale.KOREA)                     // Language : Korean,   Country : Korea
setLanguage(Locale.KOREAN)                    // Language : Korean
setLanguage(Locale.CANADA_FRENCH)             // Language : French,   Country : Canada

getLanguage Get current language as string locale.

And 2 optional override methods.

fun onBeforeLocaleChanged()
fun onAfterLocaleChanged()

This override method will be useful when you need to know when language has changed.

Back Stack 1

When setLanguage was called. Current active activity will be recreated to apply the new language.

Back Stack 2

Previous activities in back stack does not change to new language immediately. Until it back to active activity again.

Back Stack 3

Back Stack 4

Back Stack 5

Action Bar or Toolbar's title

You have to call setTitle(resId) or getActionBar().setTitle(resId) in onCreate(onSavedInstanceState: Bundle) to apply the new language.

class MainActivity: LocalizationActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        /* ... */
        setTitle(R.string.main_activity_title)
    }
}

Handle state changes

Activity will be recreate when language has changed as common behavior for configuration changes in Android. Any Activities or Fragments which hold the data should handle the state changes.

Change the language in Fragment

Language in fragment will depends on activity. So no need for additional code in Fragment.

Service

For normally usage, just extends from LocalizationService

class SimpleService : LocalizationService() {
    /* ... */
}

Or using LocalizationServiceDelegate with additional code

abstract class CustomService : Service() {
    private val localizationDelegate: LocalizationServiceDelegate by lazy {
        LocalizationServiceDelegate(this)
    }

    override fun getBaseContext(): Context {
        return localizationDelegate.getBaseContext(super.getBaseContext())
    }

    override fun getApplicationContext(): Context {
        return localizationDelegate.getApplicationContext(super.getApplicationContext())
    }

    override fun getResources(): Resources {
        return localizationDelegate.getResources(super.getResources())
    }
}

BroadcastReceiver

BroadcastReceiver is abstract class. So we cannot create LocalizationBroadcastReceiver fot you.

In this case, you need to convert the context in onReceive(context: Context, intent: Intent) to localized context with Context.toLocalizedContext() before using.

class SimpleBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val localizedContext = context.toLocalizedContext()
        /* ... */
    }
}

Language resources optimization in Android App Bundle

Change the language by library can cause a crash to your app when you publishing your app with Android App Bundle with language resources optimization enabled.

To fix this, Using the Additional Languages API in Play Core library to download the additional language before.

For more information about Additional Language API : https://android-developers.googleblog.com/2019/03/the-latest-android-app-bundle-updates.html

If you don't want to implement this feature in your code, just ignore the language resources optimization by adding the Android App Bundle configuration in your app's build.gradle

android {
    /* ... */ 
    bundle { 
        language { 
            enableSplit = false 
        } 
    } 
}

ProGuard

Normally, there's no require the ProGuard rules for this library.

But if you want to exclude this library from obfuscate and shrinking. You also can add these code to proguard-rules.pro

-keep class com.akexorcist.localizationactivity.** { *; }
-dontwarn com.akexorcist.localizationactivity.**

Change Log

See CHANGELOG.md

Licence

Copyright 2021 Akexorcist

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

RoundCornerProgressBar

[Android] Round Corner Progress Bar Library for Android
Kotlin
2,443
star
2

BluetoothSPPLibrary

[UNMAINTAINED][Android] Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller via bluetooth
Java
1,694
star
3

GoogleDirectionLibrary

[Android] Library for Google Direction API for Google Maps Android API v2
Java
574
star
4

ScreenshotDetection

[Android] Screenshot detection while user using your app
Kotlin
155
star
5

SnapTimePicker

[Android] Another Material Time Picker
Kotlin
127
star
6

GoogleDirectionAndPlaceLibrary

[Android] Library for Google Direction API and Google Place API for Google Maps Android API v2
Java
117
star
7

IOIO-CameraRobot

[Android] IOIO Robot Car with Real-time Camera from Android Device that Controlled with Another Android Device via WiFi
Java
74
star
8

Droid2JoyStick

[Android] Using android device as a gamepad to your PC or another android device.
Java
56
star
9

ConcatAdapterMultipleLayoutManager

[Android] Using ConcatAdapter with multiple LayoutManager in single RecyclerView
Kotlin
37
star
10

Glassmorphism

[Android] Glassmorphism UI experiment project
Kotlin
25
star
11

DeviceInformation

[Android] Collect android information for developer
Java
22
star
12

FileWriterCompat

[Android] File writing helper library for API Level 21+
Kotlin
18
star
13

ScreenOrientationHelper

[Android] Screen orientation event listener helper for activity in Android
Java
17
star
14

photo-on-cover-for-galaxy-z-flip5

[Android] Put your favorite photo on your cover screen and give your phone a personal touch.
Kotlin
15
star
15

SimpleTCPLibrary

[UNMAINTAINED][Android] TCP Library for android to communicate with other android device or any embedded board via TCP protocol
Java
13
star
16

Android-Sensor-Light

[Android] Using light sensor in Android devices
Java
11
star
17

INEX-RFIDReader

Communicate with Serial RFID reader via USB Host on Android
Java
10
star
18

RecyclerView-DashLine

[Android] How to implement the RecyclerView with dash line between item
Kotlin
10
star
19

CameraX-Sample

[Android] Example of CameraX in Android Jetpack Library
Kotlin
10
star
20

workstation-diagram

[Kotlin Multiplatform] My workstation's interactive diagram
Kotlin
10
star
21

ScreenChecker

[Android] Screen Checker application for development information
Kotlin
9
star
22

Android-CameraAutoFocus

Java
9
star
23

backdrop

Video and audio projection app for your streaming content on macOS
Kotlin
9
star
24

GroupFocusable

Android Custom View for prevent the view behind on-screen keyboard when edit text is focused
Kotlin
9
star
25

KnoxActivator

[Android] Samsung Knox Standard activation helper library for Android
Java
8
star
26

Android-Sensor-Gyroscope

[Android] Using gyroscope in Android devices
Java
8
star
27

Example-SamsungSDK

[Android] Example of Samsung SDK and KNOX SDK in Android
Java
7
star
28

Android-DeviceInformation

[Android] Device information for developer
Java
7
star
29

RecyclerView-ListAdapter

[Android] ListAdapter in RecyclerView
Kotlin
7
star
30

HandleStateChangesInCustomView

[Android] Handle state changes in custom view and inherited custom view
Kotlin
7
star
31

ImageResize

Effective image resizing in Android with BitmapFactory - Benchmark included
Kotlin
6
star
32

ArchitectureComponents-Repository

[Android] Repository in Android Architecture Components
Java
6
star
33

DialogExperiment

[Android] Best practice for Dialog creation in Android
Java
6
star
34

CameraSample

[Android] Example of Camera API v1 and v2 implementation
Kotlin
6
star
35

Android-AutoHideMenu

Auto Hide Menu Bar like as Google+ and Facebook
Java
6
star
36

Android-BluetoothSPP

Bluetooth Serial Port Profile library
Java
5
star
37

SleepingForLess

[Android] Sleeping For Less Reader for Android
5
star
38

coordinator-layout-catalogue

[Android] Example of coordinator layout implementation in different condition
Kotlin
5
star
39

AndroidOreo-Features

[Android] Android 8.0 Oreo Features
Java
5
star
40

Android-SplashScreen

Real splash screen for application
Java
4
star
41

ComplexRecyclerView

[Android] How I solve the problem when we have to handle very complex recycler view in Android
Kotlin
4
star
42

InstantDialog

[Android] Because I'm so boring about the Android dialog's boilerplate code
Kotlin
4
star
43

RootCheckerForSamsung

[Android] Root checking and running on Samsung devices
Java
4
star
44

LovelyRecyclerView

[Android] RecyclerView with complex layout and data
Java
4
star
45

Dagger2-Sample

[Android] Dagger 2 in Android Project with AAC
Kotlin
4
star
46

NewMvvmAac

[Android] New MVVM pattern with AAC that crystallize from iosched
Kotlin
3
star
47

Android-Sensor-Accelerometer

[Android] Using accelerometer in Android devices
Java
3
star
48

FirebaseAndroidCodelabs

[Android] Firebase project showcase in I/O Extended Thailand 2016
Java
3
star
49

RecyclerBackgroundSupportView

[Android] Add Image View behind RecyclerView with scrollable support
Kotlin
3
star
50

deep-link-generator

[React] Feel hard to test the deep link in your app? Yes, me too!
JavaScript
3
star
51

IntroToAndroidDevelopment

Android Course by Skooldio
Kotlin
3
star
52

ProgressNotification

[Android] Example of progress notification when do some asynchronous things
Kotlin
3
star
53

Android-ArchComponents

[Android] Example of Android Architecture Components
Java
2
star
54

BookApp

[Android] Sample application for communication with web service
Kotlin
2
star
55

Android-TextToSpeechThai

Example for Text to Speech with Thai language
Java
2
star
56

Android-BluetoothChat

Java
2
star
57

Android-GoogleAdMob

Using admob with google play service on android
Java
2
star
58

IOIO-Camera360

[Android] Change your IOIO board to 360 degree rotation photo capture - http://www.youtube.com/watch?v=js_ZpQCx-o8
Java
2
star
59

Shaky-FirebaseDevDay2018

[Android] Shaking game in Firebase Dev Day 2018 Bangkok
Kotlin
2
star
60

android-test-ui-hierarchy-to-json

[React] Make UI Hierarchy from Android testing more readable by parsing to JSON format
JavaScript
1
star
61

TextureViewVideoScaler

[Android] Very lightweight helper class to resize the video in texture view to fit center or crop center
Java
1
star
62

IOIO-TakeSnapshot

Java
1
star
63

sleepingforless-article-indexing-blogger

[NodeJS] Indexing the articles in Sleeping For Less by Blogger - https://www.akexorcist.com
JavaScript
1
star
64

WiFlyTCP

[Arduino] Simple TCP Communication Library for WiFly RN-XV
Arduino
1
star
65

Android-Assist

Assist action on Android
Java
1
star
66

MotoXLED

[Android] Enable a hidden LED on Moto X - Rooted required
Java
1
star
67

SimpleCustomView-Basic

[Android] Custom view with all required code
Java
1
star
68

Android-AnimationSimple

Java
1
star
69

NextzyMVP

[Android] MVP Project Structure that I use in my company project
Java
1
star
70

CodeBattle-Android

[Android] "Code Battle" for android in Firebase Dev Day
1
star
71

IOIO-Bot

Java
1
star
72

Android-ScreenshotDialog

Screenshot app screen with Dialog layout
Java
1
star
73

Simple-MVP

[Android] Simple code for MVP pattern
Java
1
star
74

DevDeviceInfo

[Android] Developer Device Information
Java
1
star
75

Example-NestedViewPager

Java
1
star
76

Example-CloudVision

Using Cloud Vision API in Android
Java
1
star
77

RecyclerView-ItemTouchHelper

[Android] ItemTouchHelper in RecyclerView
Kotlin
1
star
78

Android-CustomListView

Java
1
star
79

FlexyStepIndicator

[Android] Step Indicator view with flexibility customization
Java
1
star
80

IOIO-LCDController

Java
1
star
81

SlidingPaneLayout-Sample

[Android] Example of AndroidX SlidingPaneLayout implementation
Kotlin
1
star
82

EvenOdd

[Android] Example android app for Android CI with GitHub Actions and Firebase Test Lab
Kotlin
1
star
83

RecyclerVIew-With-Loading-Task

The answer for some guy's question on android dev facebook group at https://goo.gl/kLNlnC
Java
1
star
84

CurveSeekBar

[React] Custom your own curve seek bar in React - https://blog.nextzy.me/custom-curve-seek-bar-in-react-e1f213e87f8a
JavaScript
1
star