I'm new to android programming and I would like to do the following: I have a spinner which lets you change language. I have set it up and it works quite well. However the issue is that it does not remember the chosen language (in the spinner). So if you were to close the app and restart it, it will revert to the first item on the spinner which is english. I want to change the function in such a way that once you select an item, it remembers it.
I've set up a shared preference which remembers which language is picked. However I can't make the shared preference the lead since then I could never change the chosen language, and if I make the chosen language the lead then the preference will always follow the chosen language even at the start where the chosen language should actually follow the preference. Here's the code that I have now. I hope anyone can help me we this since I've been breaking my brain over it for a while now
pref_language = pref.getString("language", "en");
//pref_language_begin = pref.getBoolean("language_begin", false);
final Spinner spinner_languages = (Spinner) findViewById(R.id.spinner_languages);
spinner_languages.setAdapter(new CustomSpinnerAdapter(MainActivity.this, R.layout.customspinneritem, languages, language_flags));
spinner_languages.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
language_chosen = (String) parent.getItemAtPosition(position);
if (!pref_language.equals(language_chosen)) {
SetLocale(language_chosen);
pref_language = language_chosen;
edit.putString("language", pref_language);
//edit.putBoolean("language_begin", true);
edit.apply();
recreate();
}
else{
}
}
The customspinneradapter is just there to let me select both a language and a flag for it. I think I might need a second preference but I have no idea on how to implement it. The leading language at start up should be the preference but the language after choosing one in the spinner should be the chosen language. I was thinking about using an onclick listener but I'm not sure I should with spinners.
Surely there must be a more simpler way and I'm just not thinking straight. Hope you guys can help me out!