Clicking a button to switch the language

17,183

Solution 1

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.

Solution 2

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

Share:
17,183
Ron
Author by

Ron

Gamer and Programer in C#, PHP, HTML, JavaScript, CSS, Ajax and Visual Basicgooglefacebook

Updated on July 23, 2022

Comments

  • Ron
    Ron almost 2 years

    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

  • Sasha
    Sasha over 9 years
    do you know how to be in fragments with navigation drawer?its work but i have only mainactivity others are fragments so how can i change it in fragment,know if i will change it in another fragment it will intent to mainactivity?
  • Vivek Kumar Srivastava
    Vivek Kumar Srivastava over 9 years
    This thread is not related to fragment. You can ask new question about this or search same thread. By the way, you can set listener to know the fragment change event and then update navigation drawer according to your fragment requirement. See this document reference developer.android.com/reference/android/app/…
  • Abhi S
    Abhi S about 2 years
    How to change text without restart activity.