Android开发之中英文切换

首先配置文件的application标签中要添加:

android:configChanges="locale"
然后进入页面设置:
 //获取语言并显示
        if ((Integer) SPUtil.get("checkItem", 0) == 0) {
            //切换为简体中文
            Configuration config = getResources().getConfiguration();
            Resources resources = getResources();
            config.locale = Locale.CHINESE;
            DisplayMetrics dm = resources.getDisplayMetrics();
            resources.updateConfiguration(config, dm);
        } else if ((Integer) SPUtil.get("checkItem", 0) == 1) {
            //切换为英语
            Configuration config = getResources().getConfiguration();
            Resources resources = getResources();
            config.locale = Locale.ENGLISH;
            DisplayMetrics dm = resources.getDisplayMetrics();
            resources.updateConfiguration(config, dm);
        }

Dialog弹窗设置:

final String[] items = {"中文", "English"};
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle(getResources().getString(R.string.tv_language_set));
                alertBuilder.setSingleChoiceItems(items, (Integer) SPUtil.get("checkItem", 0), (dialogInterface, i) -> {
                    alertDialog.dismiss();
                    itemLanguage = items[i];
                    if ("中文".equals(itemLanguage)) {
                        SPUtil.put("checkItem", 0);
                    } else if ("English".equals(itemLanguage)) {
                        SPUtil.put("checkItem", 1);
                    }
                    changeLanguage();
                });

                alertBuilder.setNegativeButton(getResources().getString(R.string.cancel), (dialogInterface, i) -> alertDialog.dismiss());
                alertDialog = alertBuilder.create();
                alertDialog.show();
                //放在show()之后,不然有些属性是没有效果的,比如height和width
                Window dialogWindow = alertDialog.getWindow();
                WindowManager m = getWindowManager();
                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
                WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
                // 设置宽度
                p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
                p.gravity = Gravity.CENTER;//设置位置
                //p.alpha = 0.8f;//设置透明度
                dialogWindow.setAttributes(p);

退到栈顶并重启首页:

private void changeLanguage() {
        finish();
        Intent _Intent = new Intent(this, HomeActivity.class);
        _Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(_Intent);
        //清除Activity退出和进入的动画
        overridePendingTransition(0, 0);
    }

 

你可能感兴趣的:(Android)