如何使用针对Android应用的AlertDialog / Checkbox设置默认语言?

时间:2015-03-27 13:57:31

标签: java android locale android-alertdialog android-checkbox

我是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);
}

1 个答案:

答案 0 :(得分:0)

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

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