如何使用 AlertDialog/Checkbox 为 Android 应用程序设置默认语言?

How to set default language with AlertDialog/Checkbox for Android app?

我是 Android 的新手。我用两种语言(英语和荷兰语)创建了一个应用程序。默认语言为荷兰语,用户可以使用 AlertDialog 更改语言。我希望用户可以使用复选框选择英语作为默认语言。我该怎么做?

我试过了:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    if (id == R.id.action_language) {

        final String[] language =
                {
                        "Set as default language",
                };

        final boolean[] itemsChecked = new boolean[language.length];

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setIcon(R.drawable.dialogopng);
        alertDialog.setTitle("Select Language");

        alertDialog.setMultiChoiceItems(language, itemsChecked, new DialogInterface.OnMultiChoiceClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                itemsChecked[which] = isChecked;
            }
        });

        alertDialog.setPositiveButton("Dutch", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "Dutch", Toast.LENGTH_SHORT).show();
                setLocale("nl");
            }
        });

        alertDialog.setNegativeButton("English", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "English", Toast.LENGTH_SHORT).show();
                setLocale("");
            }
        });
        alertDialog.show();

        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void setLocale(String lang) {

    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, MainActivity.class);
    startActivity(refresh);
}

尝试此代码并重新加载您的 activity 以使其生效,

        Locale locale = new Locale(lang); 
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());