Changing the Language on Fly in Android
While developing an application in android, sometimes you might need to change the language on the fly. However android doesn’t provide a direct way to implement the language, so you need to adopt a different approach.
By default, Android uses the locale of the device to select the appropriate language-dependent resources.
While walking through for a solution, I came across the following blog of Guhan Sabcar, which beautifully explains how to change language pragmatically.
But this addressed one part of our problem, the other being that the Activity needs to be recreated or all the visible Textviews are required to be reset.
So I devised a way based on Guhan’s solution so that all the visible Textviews are notified at once when the locale changes and they themselves change their own text.
Following class that I have used and modified it from Guhan’s blog:
LocalHelper
We need to do 5 things here
- Create a custom TextView that we need to use everywhere
- Create a custom attribute for that TextView in XML
- Create a BroadcastReceiver in TextView as an inner-class which will capture the locale change broadcast
- Change the above mentioned LocaleHelper class to send a broadcast whenever the Locale changes.
- Use the custom TextView in all layouts and set its custom attributes.
Let us go through each step in detail:
Create a custom TextView
This done by simply extending the TextView, our new custom TextView will replace all the TextViews across all layouts.
We name it as LocaleTextView
Create a custom attribute for our custom TextView
This custom attribute will contain the name of the string resource that is set in the TextView
We need to create an attrs.xml file under the res/values folder and add the following code to it.
Now we modify our custom TextView ie LocaleTextView for accommodating this new attribute named stringResId
We add stringResId instance variable in our LocalTextView and modify the constructor to set its value.
Also, we add getter and setter methods for stringResId.
Creating a BroadcastReceiver inside LocaleTextView as a static inner class to capture locale change event
We create a static inner class named OnLocaleChangeReceiver inside our LocaleTextView, this class which extends a BroadcastReceiver is used for receiving broadcast whenever the locale is changed.
Registering and unregistering the OnLocaleChangeReceiver instance from life-cycle methods of LocaleTextView
We register and unregister the receiver inside onAttachedToWindow() and onDetachToWindow() of LocaleTextView respectively.
Final complete code of LocaleTextView
Finally using the custom LocaleTextView in layouts
Now when you change the language pragmatically all the TextViews that are visible will be updated as per the new language.
At BoTree Technologies, we build enterprise applications with our Mobile Dev team of 20+ engineers.
We also specialize in RPA, AI, Django, JavaScript and ReactJS.