Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...