I want to change language of my app by selected spinner, but at first time, don't change. After two time selected, it worked. I force to use setOnTouchListener because without it occur loop. It worked but after many times select.
This is my code:
boolean spinnerTouch=false;
Spinner s1;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (spinnerTouch) {
String text = parent.getItemAtPosition(position).toString();
if (text.equals(getString(R.string.persian))) {
lang = getResources().getString(R.string.lang_fa);
country = getResources().getString(R.string.country_ir);
onConfigurationChanged(new Configuration());
} else if (text.equals(getString(R.string.english))) {
lang = getResources().getString(R.string.lang_en);
country = getResources().getString(R.string.country_us);
onConfigurationChanged(new Configuration());
}
Utility.setPreferences(this, getResources().getString(R.string.lang), lang);
Utility.setPreferences(this, getResources().getString(R.string.country), country);
spinnerTouch = false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin=(Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
s1 = (Spinner) findViewById(R.id.spnLang);
s1.setOnItemSelectedListener(this);
s1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
spinnerTouch= true;
return false;
}
});
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
if (lang != null){
Utility.languageHelper(lang,country,newConfig,getBaseContext().getResources());
recreate();
}
}
public class Utility {
public static void languageHelper(String lang, String country, Configuration config, Resources resources) {
Locale locale = new Locale(lang,country);
config.locale = locale;
Locale.setDefault(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
}