从片段(设置)中按下名为TextView
的{{1}},在其中更改设置(语言)应用程序,如何关闭DialogFragment
,无需应用设置重启整个应用程序?
理想情况下,在DialogFragment
选择对话框中立即更改语言。随着重启一切正常。这是代码SingleChoice
:
DialogFragment
下面是我想要实现的应用程序示例:https://play.google.com/store/apps/details?id=com.funeasylearn.english
屏幕截图:
答案 0 :(得分:0)
尝试以下代码。您必须根据用户选择的语言创建新的语言环境,将其设置为当前语言环境并重新启动您的活动。请注意,如果在执行区域设置切换时它们处于活动状态,则可能必须重新启动其他活动。
public class LanguageDialogFragment extends DialogFragment {
private final String[] itemsLang = {"English", "Russian", "Ukraine"};
private final String[] items = {"en", "ru", "uk"};
private String lang;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Выберите свой родной язык")
.setSingleChoiceItems(itemsLang, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
lang = items[item];
}
}).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//When user submits, restart the activity in
//the new language
restartActivityInLanguage(lang);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Do nothing
}
});
return builder.create();
}
private void restartActivityInLanguage(String language) {
Locale locale = new Locale(language);
Configuration config = new Configuration();
config.locale = locale;
Resources resources = getResources();
resources.updateConfiguration(config, resources.getDisplayMetrics());
getActivity().recreate();
}
}