Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking a button to switch the language

When I click on the "sub_changelang" button, it should change the program language to French for example. I got the following code to change the locale but I have no idea how to refresh/ pdate the app to change the language to French.

Button cl = (Button) findViewById(R.id.sub_changelang); 
cl.setOnClickListener(new OnClickListener()
{ 
    @Override 
    public void onClick(View v)
    { 
        Locale locale = new Locale("fr_FR"); 
        Locale.setDefault(locale); 
        Configuration config = new Configuration(); 
        config.locale = locale; 
    } 
});

It doesn't work. How can I fix it? I tried to add:

MainActivity.this.getResources().updateConfiguration(config, MainActivity.this.getResources().getDisplayMetrics());

but it didn't work. I also tried:

getBaseContext().getResources().updateConfiguration(config,
                          getBaseContext().getResources().getDisplayMetrics());

and it didn't work either.

android:configChanges="locale"

is set inside the AndroidMainfest.xml under application -> activity

like image 770
Ron Avatar asked Apr 12 '13 11:04

Ron


2 Answers

You can use activity.this.recreate().But it will support from API level 11.

like image 188
AndiM Avatar answered Nov 10 '22 06:11

AndiM


I am using this code to set locale

String languageToLoad  = "fr_FR";
     Locale locale = new Locale(languageToLoad); 
     Locale.setDefault(locale);
     Configuration config = new Configuration();
     config.locale = locale;
     context.getResources().updateConfiguration(config,context.getResources().getDisplayMetrics());

Intent intent = new Intent(XYZ.this, XYZ.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

here context is application Base Context. Please also try "fr" instead of "fr_FR" because I am working for Arabic locale and its working fine.

You need to restart your Activity after changing locale.

like image 25
Vivek Kumar Srivastava Avatar answered Nov 10 '22 05:11

Vivek Kumar Srivastava