I am developing an Android application that should work on both types of devices: phone, tv and tv box. To do this, I created resources with a TV modifier (for example, textSizes in dimens that will change automatically depending on the uimode), but the problem is that TV boxes use mobile insead of TV. How to change the uimode on app start in order to use dimens with tv modifer?
I've already tried this, but it doesn't work.
config.uiMode = Configuration.UI_MODE_TYPE_TELEVISION
resources.updateConfiguration(config, resources.displayMetrics)
Finally, I've found a solution! Maybe it would be helpful for someone!
So, I must put it into attachBaseContext instead of onCreate
override fun attachBaseContext(context: Context?) {
super.attachBaseContext(context)
if (context != null) {
SettingsData.initDeviceType(context)
if (SettingsData.deviceType == DeviceType.TV) {
resources.configuration.uiMode = uiMode
resources.configuration.setTo(resources.configuration)
}
}
}
Also, having switched to another device mode, you have to reload an activity. I've tried finish() StartActivity(intent), but it doesn't work properly. So to fix it up I use ProcessPhoenix lib:
fun refreshActivity() {
ProcessPhoenix.triggerRebirth(this)
}
Warning! If you are using setRequestedOrientation in your MainActivity, it could trigger configuration to change with old uimode.
In application the language doesn't change completely. I select English. It say English. But when I go to another activity. The language change to primitive language. After I go to the main activity. The language is primative language. But when I click English or French(again) not any problem at all.
I think I didn't tell well. I hope you can understand well with video :
https://drive.google.com/file/d/1-5QL_5kdzg8d7QDe8UF8cwVii_-1S4JR/view?usp=sharing
The code for changing language :
public void dilidegistir(String dil){
Resources activityRes = getResources();
Configuration activityConf = activityRes.getConfiguration();
Locale newLocale = new Locale(dil);
activityConf.setLocale(newLocale);
activityRes.updateConfiguration(activityConf, activityRes.getDisplayMetrics());
Resources applicationRes = getApplicationContext().getResources();
Configuration applicationConf = applicationRes.getConfiguration();
applicationConf.setLocale(newLocale);
applicationRes.updateConfiguration(applicationConf,
applicationRes.getDisplayMetrics());
finish();
startActivity(getIntent());
}
How can I solve this problem?
I need your help.
I don't know why you're trying to change the language at runtime (normally it should be handled on the system level based on device's settings), but if you really need it check out this article: https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
I hope it's helpful.
I have a multilingual app with primary language English and secondary language Arabic.
As described in the documentation,
I have added android:supportsRtl="true" in the manifest.
I have changed all xml properties with left and right attributes to start and end respectively.
I have added Arabic language strings in strings-ar (and similarly for other resources).
The above setup works properly. After changing the Locale to ar-AE, Arabic text & resources are correctly displayed in my Activities.
However, every time I navigate to an Activity with a WebView
and/or a WebViewClient, the locale, text and layout direction
abruptly revert to the device default.
Further hints:
This is occurring only on a Nexus 6P with Android 7.0. Everything works properly on Android 6.0.1 and below.
The abrupt shift in locale happens only when I navigate to an Activity that has a WebView and/or a WebViewClient (and I have several). It does not occur on any of the other Activities.
Android 7.0 has multi-locale support, allowing the user to set more than one default locale. So if I set the primary locale to Locale.UK:
Then on navigating to the WebView, the locale changes from ar-AE
to en-GB.
Android 7.0 API changes:
As indicated in the list of API changes, new methods pertaining to locale have been added to the following classes in API 24:
Locale:
Locale.getDefault(...)
Locale.setDefault(...)
Configuration:
getLocales()
setLocales(...)
However, I am building my app with API 23, and am not using any of
these new methods.
Furthermore ...
The problem occurs on the Nexus 6P emulator as well.
To get the default locale, I am using Locale.getDefault().
To set the default locale, I am using the following code:
public static void setLocale(Locale locale){
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
Context context = MyApplication.getInstance();
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
}
Has anyone encountered this problem before? What is the reason for it, and how do I resolve this?
References:
1. Native RTL support in Android 4.2.
2. Multilingual Support - Language and Locale.
3. Be wary of the default locale.
Ted Hopp's answer managed to solve the problem, but he didn't address the question of why this occurs.
The reason is the changes made to the WebView class and its support package in Android 7.0.
Background:
Android's WebView is built using WebKit. While it was originally a part of AOSP, from KitKat onwards a decision was made to spin off WebView into a separate component called Android System WebView. It is essentially an Android system app that comes pre-installed with Android devices. It is periodically updated, just like other system apps such as Google Play Services and the Play Store app. You can see it in your list of installed system apps:
Android 7.0 changes:
Starting with Android N, the Chrome app will be used to render any/all WebViews in third-party Android apps. In phones that have Android N out-of-the-box, the Android WebView System app is not present at all. In devices that have received an OTA update to Android N, the Android System WebView is disabled:
and
Moreover, multi-locale support has been introduced, with devices having more than one default language:
This has an important consequence for apps that have multiple languages. If your app has WebViews, then those are rendered using the Chrome app. Because Chrome is an Android app in itself, running in its own sandboxed process, it will not be bound to the locale set by your app. Instead, Chrome will revert to the primary device locale. For example, say your app locale is set to ar-AE, while the primary locale of the device is en-US. In this case, the locale of the Activity containing a WebView will change from ar-AE to en-US, and strings and resources from the corresponding locale folders will be displayed. You may see a mish-mash of LTR and RTL strings/resources on those Activitys that have WebViews.
The Solution:
The complete solution to this problem consists of two steps:
STEP 1:
First, reset the default locale manually in every Activity, or at least every Activity that has a WebView.
public static void setLocale(Locale locale){
Context context = MyApplication.getInstance();
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
Locale.setDefault(locale);
configuration.setLocale(locale);
if (Build.VERSION.SDK_INT >= 25) {
context = context.getApplicationContext().createConfigurationContext(configuration);
context = context.createConfigurationContext(configuration);
}
context.getResources().updateConfiguration(configuration,
resources.getDisplayMetrics());
}
Call the above method before calling setContentView(...) in the onCreate() method of all your Activities. The locale parameter should be the default Locale that you wish to set. For example, if you wish to set Arabic/UAE as the default locale, you should pass new Locale("ar", "AE"). Or if you wish to set the default locale (i.e. the Locale that is automatically set by the operating system), you should pass Locale.US.
STEP 2:
Additionally, you need to add the following line of code:
new WebView(this).destroy();
in the onCreate() of your Application class (if you have one), and wherever else the user may be changing the language. This will take care of all kinds of edge cases that may occur on app restart after changing the language (you may have noticed strings in other languages or with the opposite alignment after changing the language on Activities that have WebViews on Android 7.0++).
As an addendum, Chrome custom tabs are now the preferred way of rendering in-app web pages.
References:
1. Android 7.0 - changes for WebView.
2. Understanding WebView and Android security patches.
3. WebView for Android.
4. WebView: From "Powered by Chrome" to straight up Chrome.
5. Nougat WebView.
6. Android 7.0 Nougat.
7. Android N Mysteries, Part 1: Android System WebView is just "Chrome" Now?.
Your code seems to be setting the locale in the configuration for the app itself (MyApplication.getInstance()). However, you need to update the configuration for the activity context before inflating the activity's content view. I've found that modifying the app's context isn't enough (and, as it turns out, isn't even necessary). If I don't update each activity context, then the behavior is inconsistent across activities.
The way I approach this is to subclass AppCompatActivity (or Activity, if not using the compatibility library) and then derive all my activity classes from that subclass. Here's a simplified version of my code:
public class LocaleSensitiveActivity extends AppCompatActivity {
#Override protected void onCreate(Bundle savedInstanceState) {
Locale locale = ... // the locale to use for this activity
fixupLocale(this, locale);
super.onCreate(savedInstanceState);
...
}
static void fixupLocale(Context ctx, Locale newLocale) {
final Resources res = ctx.getResources();
final Configuration config = res.getConfiguration();
final Locale curLocale = getLocale(config);
if (!curLocale.equals(newLocale)) {
Locale.setDefault(newLocale);
final Configuration conf = new Configuration(config);
conf.setLocale(newLocale);
res.updateConfiguration(conf, res.getDisplayMetrics());
}
}
private static Locale getLocale(Configuration config) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return config.getLocales().get(0);
} else {
//noinspection deprecation
return config.locale;
}
}
}
Then I make sure to call super.onCreate(savedInstanceState) in each subclass's onCreate() method before calling any methods (such as setContentView()) that use the context.
This has an important consequence for apps that have multiple languages. If your app has WebViews, then those are rendered using the Chrome app. Because Chrome is an Android app in itself, running in its own sandboxed process, it will not be bound to the locale set by your app. Instead, Chrome will revert to the primary device locale. For example, say your app locale is set to ar-AE, while the primary locale of the device is en-US. In this case, the locale of the Activity containing a WebView will change from ar-AE to en-US, and strings and resources from the corresponding locale folders will be displayed. You may see a mish-mash of LTR and RTL strings/resources on those Activitys that have WebViews.
The Solution:
The complete solution to this problem consists of two steps:
STEP 1:
First, reset the default locale manually in every Activity, or at least every Activity that has a WebView.
public static void setLocale(Locale locale){
Context context = MyApplication.getInstance();
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
Locale.setDefault(locale);
configuration.setLocale(locale);
if (Build.VERSION.SDK_INT >= 25) {
context = context.getApplicationContext().createConfigurationContext(configuration);
context = context.createConfigurationContext(configuration);
}
context.getResources().updateConfiguration(configuration,
resources.getDisplayMetrics());
}
Call the above method before calling setContentView(...) in the onCreate() method of all your Activities. The locale parameter should be the default Locale that you wish to set. For example, if you wish to set Arabic/UAE as the default locale, you should pass new Locale("ar", "AE"). Or if you wish to set the default locale (i.e. the Locale that is automatically set by the operating system), you should pass Locale.US.
STEP 2:
Additionally, you need to add the following line of code:
new WebView(this).destroy();
in the onCreate() of your Application class (if you have one), and wherever else the user may be changing the language. This will take care of all kinds of edge cases that may occur on app restart after changing the language (you may have noticed strings in other languages or with the opposite alignment after changing the language on Activities that have WebViews on Android 7.0++).
As an addendum, Chrome custom tabs are now the preferred way of rendering in-app web pages.
After reading all answers I found out that there is something missing in each one so here is the solution that worked for me so far. Since the WebView overrides the language configuration of the activity's context and application context, you must make sure each time this happens you call a method that resets those changes back. In my case I wrote following class that my activities which present this problem extend (those showing a WebView):
public class WebViewFixAppCompatActivity extends AppCompatActivity {
private Locale mBackedUpLocale = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mBackedUpLocale = getApplicationContext().getResources().getConfiguration().getLocales().get(0);
}
}
#Override
protected void onStop() {
super.onStop();
fixLocale();
}
#Override
public void onBackPressed() {
fixLocale();
super.onBackPressed();
}
/**
* The locale configuration of the activity context and the global application context gets overridden with the first language the app supports.
*/
public void fixLocale() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Resources resources = getResources();
final Configuration config = resources.getConfiguration();
if (null != mBackedUpLocale && !config.getLocales().get(0).equals(mBackedUpLocale)) {
Locale.setDefault(mBackedUpLocale);
final Configuration newConfig = new Configuration(config);
newConfig.setLocale(new Locale(mBackedUpLocale.getLanguage(), mBackedUpLocale.getCountry()));
resources.updateConfiguration(newConfig, null);
}
// Also this must be overridden, otherwise for example when opening a dialog the title could have one language and the content other, because
// different contexts are used to get the resources.
Resources appResources = getApplicationContext().getResources();
final Configuration appConfig = appResources.getConfiguration();
if (null != mBackedUpLocale && !appConfig.getLocales().get(0).equals(mBackedUpLocale)) {
Locale.setDefault(mBackedUpLocale);
final Configuration newConfig = new Configuration(appConfig);
newConfig.setLocale(new Locale(mBackedUpLocale.getLanguage(), mBackedUpLocale.getCountry()));
appResources.updateConfiguration(newConfig, null);
}
}
}
}
The idea posted by #Tobliug to save the initial configuration before the WebView overrides it worked for me, in my particular case I found this to be more easy to implement than other solutions posted.
Important is that the fix method gets called after exiting the WebView, e.g. when pressing back and in onStop.
If the webView is shown in a dialog you must take care the fix method is called after dismissing the dialog, mostly in onResume and/or onCreate. And if the webView is directly loaded in onCreate of the Activity and not afterwards in a new fragment the fix must also be called directly after setContentView before the activity's title is set, etc. If the WebView is loaded inside a fragment in the activity, call the activity in onViewCreated of the fragment and the activity should call the fix method.
Not all activities need to extend the class above as noted in an aswer, that's an overkill and not necessary.
This issue also does not get solved replacing the WebView by Google Chrome Tabs or opening an external browser.
If you really need your ressources configuratoin to have the whole list of languages set and not only one, then you would need to merge this solution with the one at https://gist.github.com/amake/0ac7724681ac1c178c6f95a5b09f03ce
In my case it was not necessary.
I also did not find necessary to call new WebView(this).destroy(); as noted in an answer here.
Same issue here. I have a dirty, but simple, solution.
Because I observe that the locale is still good in the Activity.onCreate(...) function and no more valid in the Activity.onPostCreate(...) function, I just save the Locale and force it at the end of the onPostCreate(...) function.
Here we go :
private Locale backedUpLocale = null;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
backedUpLocale = getApplicationContext().getResources().getConfiguration().locale;
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
changeLocale(backedUpLocale);
}
Bonus - the change locale function :
public void changeLocale(final Locale locale) {
final Configuration config = res.getConfiguration();
if(null != locale && !config.locale.equals(locale)) {
Locale.setDefault(locale);
final Configuration newConfig = new Configuration(config);
if(PlatformVersion.isAtLeastJellyBeanMR1()) {
newConfig.setLocale(new Locale(locale.getLanguage()));
} else {
newConfig.locale = new Locale(locale.getLanguage());
}
res.updateConfiguration(newConfig, null);
}
}
Hopes it will help.
I want to add one more use-case here:
When pressing back from webview activity(i.e. Showing payment screen and user press back button), onCreate() of previous activity does not execute, So that language got reset again. To keep it bug free, We must reset app locale in onResume() of base Activity.
private static void updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.setLocale(locale);
config.setLayoutDirection(locale);
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
}
Call above method in onResume() of base activity or atleast in webview activity.
Edit:
If you are dealing with Fragments, make sure this method called when user exit from webview.
I have noticed that this happens only the first time you use a web view in the app , but it will not happen after that (i.e if the language is changed from inside the app and you opened a web view -again- or another webview ,then this time the webview will not change back the language as it did in the first time.
so based on that, a simple solution that I have done is I have added a webview with visibility gone to my very first activity in the app(or the host activity if you use single activity app with fragments) then I apply my locale in that activity's onCreate method after the call to setContentView.So in my activity.xml I will have :
<WebView
android:id="#+id/webview"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
and in my activity :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)//at this moment and because there is the webview in the xml, the language will be reverted to the device's language
updateLocal(this ,"en")//this reset it back to whatever language you want to use(from shared preferences for example )
}
and updateLocal having code like following :
fun updateLocale(
c: Context,
languageToSwitchTo: String
): Context {
val locale = Locale(languageToSwitchTo)
Locale.setDefault(locale)
var context = c
val resources = context.resources
val configuration: Configuration = resources.configuration
configuration.setLayoutDirection(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val localeList = LocaleList(locale)
LocaleList.setDefault(localeList)
configuration.setLocales(localeList)
} else {
configuration.locale = locale
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
context = context.createConfigurationContext(configuration)
}
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
In Android N, when you do new WebView(), it will add /system/app/WebViewGoogle/WebViewGoogle.apk to resource path. And if it was not added to the path already, it will cause Resource recreate (only the first time you use WebView in the app).
So if you want to solve the problem, just do new WebView(applicationContext) in Application#OnCreate() before you change the Locale.
If you know Chinese, you can read this blog.
None of the answers above helped me, I managed to reset app locale again inside onStop() method of the activity containing the Webview
If you are using the WebView only to display rich text (Text with some paragraphs or bold and italic text in different font sizes), then you can use TextView and Html.fromHtml() instead. TextViews have no issue with locale settings ;-)
Just Change Parameter For SEt Local Method From Passing BaseContext To "this" Or Exact activity Specially On android 7.0 and older
I'm facing the same issue in the fragment.
Resolving this by setting language again in the onDestroyView function
#Override
public void onDestroyView() {
Utils.setLanguage(requireActivity());
super.onDestroyView();
}
I fixed the problem of pronunciation by changing the language of HTML using the lang tag.
HTML Language Accessibility
I want my language to change dynamically and I am trying to use onConfigurationChanged but it is not being called. I have a MainActivity that creates my action bar and viewpager. The rest of my pages are Fragments. In my SettingsFragment I have a button to switch the language to French.
langChange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vi) {
MainActivity main = (MainActivity)getActivity();
main.langChange();
}
});
Then in my MainActivity I have
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
if (locale != null){
newConfig.locale = locale;
Locale.setDefault(locale);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
}
public void langChange(){
if(currentLanguage == FRENCH_LANGUAGE){
locale = new Locale("en");
Locale.setDefault(locale);
Configuration c = getBaseContext().getResources().getConfiguration();
c.locale = locale;
getBaseContext().getResources().updateConfiguration(c,getBaseContext().getResources().getDisplayMetrics());
currentLanguage = "English";
}
else if(currentLanguage == ENGLISH_LANGUAGE){
locale = new Locale("fr");
Locale.setDefault(locale);
Configuration c = getBaseContext().getResources().getConfiguration();
c.locale = locale;
getBaseContext().getResources().updateConfiguration(c,getBaseContext().getResources().getDisplayMetrics());
currentLanguage = "French";
}
actionBar.setSelectedNavigationItem(actionBar.getTabCount() - 1); //This just puts it back to the settings tab
}
The onConfigurationChanged is not being called. In my manifest I have:
<activity android:name="MainActivity" android:screenOrientation="portrait" android:configChanges="locale"></activity>
I have tried adding one or all of these options orientation|keyboardHidden|screenSize with no success.
The reason for all of this is because I want to change the actionBar text and all the other text once I click the button. I have a separate strings file for French.
Any help would be great.
You have to define android:configChanges="layoutDirection|locale" in order for onConfigurationChanged() to be called.
Ok, I've looked into this a bit.
I'm not sure, why the onConfigurationChanged method isn't called, so I'm hoping someone can enlighten us on this part.
In my search I stumbled upon this tutorial , which actually change the Locale, by changing the configuration.
Your code looks a lot like this tutorial actually ;-)
Anyways, the important thing about the tutorial and the code is this method:
private void updateTexts() {
txt_hello.setText(R.string.hello_world);
btn_en.setText(R.string.btn_en);
btn_ru.setText(R.string.btn_ru);
btn_fr.setText(R.string.btn_fr);
btn_de.setText(R.string.btn_de);
}
This is where the "magic" happens; after you've changed your locale you will need to reload your resources and since you told Android you want to handle some configurations on your own you need to specifically reload all your text, by setting your UI items texts again.
When this is done, the app will load the strings from the specific locales folder.
The answer to why Android behaves this way, can be found in the official documentation for the Activity saying:
[...]
This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.
The guy writing the tutorial was kind enough to add the whole tutorial project as a download, so I recommend you go check it out to see how it's working, because it is working ;-) You can outcomment the onConfigurationChanged method, as it doesn't seem to be doing anything.
Hope this helps.
How do I localize application so it uses specific locale regardless of what locale set on device? I want make it possible for users to set language of their choice.
So far I have code like this in my Application class:
#Override
public void onCreate()
{
//Set locale
String l = Preferences.getLocale(getApplicationContext());
if (!l.equals(""))
{
Locale locale = new Locale(l);
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(
config, getBaseContext().getResources().getDisplayMetrics());
}
LogData.InsertMessage(getApplicationContext(), "Application started");
}
Problem that I have is that it seems like I display in set locale just fine (TextViews)
But Menu captions and toasts will fall to default locale.
Is there any 1-2-3 on how to get it working properly? I uses 2.2 version
This post explains how to force localization in your app.
Ok, I figured why I had this problem.. I needed to override onConfigurationChanged in my application class. That is much more elegant solution than to specify locale on each Activity.