Anas code Anas code - 4 months ago 18
Android Question

Android - Changing Locale language within the app itself

My app supports 3 languages (english, french and arabic). I have already translated all ressources (values string and drawables files) and it work perfect according to the language set in the user device.

The app consists principally of two activities : mainActivity and Game Activity. mainActivity contain a button (Play) which leads to the GameActivity according to the device language. For example if language is english it will launch Game Activity, if f language is french it will launch GameFr Activity, and if language is arabic it will launch GameAr Activity.

Play.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Locale.getDefault().getLanguage().equals("ar")){
Intent intgame=new Intent(MainActivity.this,GameAr.class);
startActivity(intgame);
}

else {
if (Locale.getDefault().getLanguage().equals("fr")){
Intent intgame=new Intent(MainActivity.this,GameFr.class);
startActivity(intgame);
}

else {
Intent intgame=new Intent(MainActivity.this,Game.class);
startActivity(intgame);
}
}
}
});


However, I would like to add 3 ImageView (flags) in the MainActivity through which users can change the language of the application, for this I added the following:

en = (ImageView) findViewById(R.id.en);
fr = (ImageView) findViewById(R.id.fr);
ar = (ImageView) findViewById(R.id.ar);

en.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setLocale("en");
Intent uo = new Intent(MainActivity.this,Game.class);
startActivity(uo);
}
});

fr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setLocale("fr");
Intent uo = new Intent(MainActivity.this,GameFr.class);
startActivity(uo);
}
});

ar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setLocale("ar");
Intent uo = new Intent(MainActivity.this,GameAr.class);
startActivity(uo);
}
});


Nevertheless, when a user with a device which the language is set to english click the French flag, it will get successfully the french activity. However, if he comes back to the previous page and click on the button (Play), the page displayed is the one corresponding to the activity in English but with the resources (string values and Drawables) French.

This is because the following function:

if (Locale.getDefault().getLanguage().equals("ar"))


always test the language of the device, not the language that the user chose in the app.

is there a function that can give me the language chosen by the SetLocale function? or I should use a variable transfer between activities?

how can I fix this, do you have better suggestions?

Answer

use this

 Locale.setDefault("Your Locale");
Comments