通过对话框列表更改Android应用程序区域设置

时间:2015-01-29 12:48:56

标签: java android sharedpreferences locale

由于受欢迎的请求,我正在尝试为我的应用添加语言转换器。我添加了一个列表对话框,然后通过它更改了语言环境,如下面的代码示例所示。但每当用户关闭并重新打开应用程序或更改方向时,它都会恢复为系统语言。我已阅读有关共享首选项的信息,但我无法理解如何使用它们进行设置?我该怎么办呢?以下是我的相关代码

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
            if (android.R.id.home == item.getItemId()) {
                    finish();

                    return super.onOptionsItemSelected(item);
            }

            switch (item.getItemId()) {
            case R.id.action_upgrade:
                    Intent launchNewIntent = new Intent(
                                    "android.intent.action.VIEW",
                                    Uri.parse("https://play.google.com/store/apps/details?id=com.nath.thecompletembguidepro"));
                    startActivity(launchNewIntent);
                    return true;
            case R.id.action_language:
                    final CharSequence[] items = { "English", "German", "Spanish",
                                    "Potuguese" };

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Change MB Guide Language");
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int pos) {
                                    if (pos == 0) {

                                            setLocale("en");
                                    } else if (pos == 1) {

                                            setLocale("de");
                                    } else if (pos == 2) {

                                            setLocale("es");
                                    } else if (pos == 3) {

                                            setLocale("pt");
                                    }

                            }
                    });

                    AlertDialog alert = builder.create();
                    alert.show();

                    return true;

这是完整的活动代码

public class MainActivity extends ActionBarActivity {
protected boolean small;
Locale myLocale;

@Override
protected void onStart() {
    super.onStart();
    RateThisApp.onStart(this);
    RateThisApp.showRateDialogIfNeeded(this);
    YoYo.with(Techniques.SlideInDown).duration(700)
            .playOn(findViewById(android.R.id.list));
    YoYo.with(Techniques.SlideInDown).duration(1200)
            .playOn(findViewById(R.id.fabbutton));
}

private FeedbackDialog feedBack;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    StartAppSDK.init(this, "105864370", "207677226", new SDKAdPreferences()
            .setAge(10).setGender(Gender.MALE), false);
    LayoutInflater i = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    final View v = i.inflate(R.layout.mainactivityfavlayout, null);
    final LinearLayout root = new LinearLayout(this);
    root.addView(v);
    setContentView(root);
    getSupportActionBar().setIcon(R.drawable.newbook);
    small = false;
    final Fab mFab = (Fab) v.findViewById(R.id.fabbutton);
    mFab.setFabDrawable(getResources().getDrawable(
            R.drawable.ic_action_thumbs_up_down));
    mFab.setFabColor(Color.parseColor("#795548"));
    mFab.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (!small) {
                small = true;
                feedBack.show();

            } else {
                small = false;
                feedBack.show();

            }
        }
    });

    boolean installed = appInstalledOrNot("com.br4mmie.minebuilder");
    if (installed) {

        System.out.println("App already installed on your phone");
    } else {
        System.out.println("App is not installed on your phone");
        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);
        builder.setTitle(getString(R.string.info));
        builder.setMessage(getString(R.string.mbnotfounderror));
        builder.setPositiveButton(R.string.download,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent launchNewIntent5 = new Intent(
                                "android.intent.action.VIEW",
                                Uri.parse("https://play.google.com/store/apps/details?id=com.br4mmie.minebuilder"));
                        startActivity(launchNewIntent5);
                    }
                });
        builder.setNegativeButton(getString(R.string.ignore),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertdialog = builder.create();
        alertdialog.show();

    }

    final CardListView list = (CardListView) findViewById(android.R.id.list);
    CardAdapter<Card> adapter = new CardAdapter<Card>(this,
            android.R.color.black);
    list.setAdapter(adapter);
    adapter.add(new CardHeader(getString(R.string.hello)));
    adapter.add(new Card((getString(R.string.recipes)),
            ((getString(R.string.recipesbio)))).setThumbnail(getResources()
            .getDrawable(R.drawable.bookicon)));
    adapter.add(new Card((getString(R.string.id)),
            ((getString(R.string.idbio)))).setThumbnail(getResources()
            .getDrawable(R.drawable.idicon)));
    adapter.add(new Card((getString(R.string.mobs)),
            ((getString(R.string.mobsbio)))).setThumbnail(getResources()
            .getDrawable(R.drawable.mobsicon)));
    adapter.add(new Card((getString(R.string.biomesactitle)),
            ((getString(R.string.biomesbio)))).setThumbnail(getResources()
            .getDrawable(R.drawable.biomesicon)));
    adapter.add(new Card((getString(R.string.title_activity_ad)),
            ((getString(R.string.adbio)))).setThumbnail(getResources()
            .getDrawable(R.drawable.miscicon)));
    list.setOnCardClickListener(new CardClickListener() {

        @Override
        public void onCardClick(int index,
                @SuppressWarnings("rawtypes") CardBase card, View view) {
            Log.i("MBGuide", "Clicked a Button on homepage");
            if (index == 1)
                startActivity(new Intent(MainActivity.this,
                        RecipeChooserActivity.class));
            if (index == 2)
                startActivity(new Intent(MainActivity.this,
                        IDActivity.class));
            if (index == 3)
                startActivity(new Intent(MainActivity.this,
                        NewMobsActivity.class));
            if (index == 4)
                startActivity(new Intent(MainActivity.this,
                        DimensionChooserActivity.class));
            if (index == 5)
                startActivity(new Intent(MainActivity.this,
                        AdActivity.class));

        }
    });

    getSupportActionBar().setIcon(R.drawable.newbook);

    android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color
            .parseColor("#795548")));

    SystemBarTintManager tintManager = new SystemBarTintManager(this);
    tintManager.setStatusBarTintEnabled(true);
    tintManager.setTintColor(Color.parseColor("#5D4037"));
    FeedbackSettings feedbackSettings = new FeedbackSettings();
    feedbackSettings.setText(getString(R.string.feedbackinfo));
    feedbackSettings.setTitle(getString(R.string.feedbacktitle));
    feedbackSettings.setReplyTitle(getString(R.string.feedbacknewmessage));
    feedbackSettings
            .setReplyCloseButtonText(getString(R.string.feedbackclose));
    feedbackSettings
            .setReplyRateButtonText(getString(R.string.feedbackrate));
    feedbackSettings.setBugLabel(getString(R.string.feedbackbug));
    feedbackSettings.setIdeaLabel(getString(R.string.feedbackidea));
    feedbackSettings.setQuestionLabel(getString(R.string.feedbackquestion));
    feedBack = new FeedbackDialog(this, "AF-E0C9EDA7599B-26",
            feedbackSettings);

}

@Override
protected void onPause() {
    super.onPause();
    feedBack.dismiss();

}

@Override
protected void onResume() {
    super.onResume();
    YoYo.with(Techniques.SlideInDown).duration(700)
            .playOn(findViewById(android.R.id.list));

}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    if (android.R.id.home == item.getItemId()) {
        finish();

        return super.onOptionsItemSelected(item);
    }

    switch (item.getItemId()) {
    case R.id.action_upgrade:
        Intent launchNewIntent = new Intent(
                "android.intent.action.VIEW",
                Uri.parse("https://play.google.com/store/apps/details?id=com.nath.thecompletembguidepro"));
        startActivity(launchNewIntent);
        return true;
    case R.id.action_language:
        final CharSequence[] items = { "English", "German", "Spanish",
                "Potuguese" };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Change MB Guide Language");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int pos) {
                if (pos == 0) {

                    setLocale("en");
                } else if (pos == 1) {

                    setLocale("de");
                } else if (pos == 2) {

                    setLocale("es");
                } else if (pos == 3) {

                    setLocale("pt");
                }

            }
        });

        AlertDialog alert = builder.create();
        alert.show();

        return true;
    case R.id.action_dlmb:
        Intent launchNewIntent13 = new Intent(
                "android.intent.action.VIEW",
                Uri.parse("https://play.google.com/store/apps/details?id=com.br4mmie.minebuilder"));
        startActivity(launchNewIntent13);
        return true;
    case R.id.action_about:
        Intent launchNewIntent3 = new Intent(MainActivity.this,
                AboutActivity.class);
        startActivity(launchNewIntent3);
        return true;
    case R.id.action_credits:
        Intent launchNewIntent1 = new Intent(MainActivity.this,
                SixthActivity.class);
        startActivityForResult(launchNewIntent1, 0);
        return true;
    case R.id.action_feedback:
        Intent launchNewIntent11 = new Intent(
                "android.intent.action.VIEW",
                Uri.parse("https://www.youtube.com/watch?v=mTrNFlR8Mh4&feature=youtu.be"));
        startActivity(launchNewIntent11);
        return true;
    case R.id.action_videohub:
        AlertDialog.Builder builder1 = new AlertDialog.Builder(
                MainActivity.this);
        builder1.setTitle(getString(R.string.mbvhtitle));
        builder1.setMessage(getString(R.string.mbvhdescription));
        builder1.setPositiveButton(getString(R.string.download),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent launchNewIntent5 = new Intent(
                                "android.intent.action.VIEW",
                                Uri.parse("https://play.google.com/store/apps/details?id=com.nath.mbvideohub"));
                        startActivity(launchNewIntent5);
                        Toast.makeText(MainActivity.this,
                                "Requires Network Connection",
                                Toast.LENGTH_SHORT).show();
                    }
                });
        builder1.setNegativeButton(getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertdialog = builder1.create();
        alertdialog.show();
    }
    return false;
}

{
    ;

}

}

1 个答案:

答案 0 :(得分:0)

我会使用偏好屏幕制作设置菜单。然后用户可以随心所欲地改变他的语言。

Settings menu with Preferencescreen

实施例

        SharedPreferences settings = getActivity().getSharedPreferences(
                PREFS_NAME, MODE_PRIVATE);

        // EditorObject to store values!
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("Name", mEtxtName.getText().toString());
        editor.putString("Email", mEtxtEmail.getText().toString());


        editor.commit();

    // GET VALUES IN FRAGMENT FROM PREFERENCES.
    SharedPreferences settings = getActivity().getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    mTxtShowEmail.setText(settings.getString("Email", "Default@email.com"));
    mTxtShowName.setText(settings.getString("Name", "Defaultname"));
相关问题