簡體   English   中英

如何使用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);
}

嘗試使用此代碼,然后重新加載您的活動以使其生效,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM