我将用户选择的语言保存在setSingleChoiceItems alertDialog
. 我希望当应用程序启动时,所有内容都以正确的语言显示,并且当用户想要选择一种新语言时,当他按下 listView 以获取警报对话框时,他可以看到已经选择的语言已选中的右单选按钮。但我似乎无法加载数据。在 onCreate 中,我正在调用我的函数LoadPrefs();
,但这似乎并没有奏效。所以我想我在这里做错了什么?
是否也可以在我的开始活动中加载数据,因为我正在保存语言首选项,它应该在应用程序打开时直接更改,而不是在用户到达时SettingsActivity
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
LoadPrefs();
registerClickCallBack();
ListView listView = (ListView) findViewById(R.id.settingsList);
String[] values = new String[] { "Language", "Facebook login", "About" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
private void LoadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String langValue = sp.getString("lang", "en");
}
private void savePrefs(String lang, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(lang, value);
edit.commit();
}
private String lang(String lang){
String language = lang;
Locale local;
Configuration config;
local = new Locale(language);
Locale.setDefault(local);
config = new Configuration();
config.locale = local;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
savePrefs("lang", lang);
return lang;
}
private void registerClickCallBack() {
ListView list = (ListView) findViewById(R.id.settingsList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
String langEN = getResources().getString(R.string.langEN);
String langFR = getResources().getString(R.string.langFR);
String langNL = getResources().getString(R.string.langNL);
String langTitle = getResources().getString(R.string.langTitle);
final CharSequence[] items = {langEN, langFR, langNL};
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setTitle(langTitle);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
lang("en");
break;
case 1:
lang("fr");
break;
case 2:
lang("nl");
break;
}
dialog.dismiss();
}
});
final AlertDialog levelDialog = builder.create();
levelDialog.show();
}
}
});
}
}