app内切换语言

最近项目要做到中英文切换的功能,调查了很久现在讲解及记录一下

首先android 支持多语言的操作,先要在你的res的values中新建一套你的语言系统的strings.xml

右键点击res 

选中android resource file 并选择locale 

这时点击右面的那个箭头

这时可以选择你要的那个语言

以上是我们的准备工作,下面直接代码

public class LocaleUtils {
     //中文
    public static final Locale LOCALE_CHINESE = Locale.CHINESE;
    /**
     * 英文
     */
    public static final Locale LOCALE_ENGLISH = Locale.ENGLISH;
    /**
     * 保存SharedPreferences的文件名
     */
    private static final String LOCALE_FILE = "LOCALE_FILE";
    /**
     * 保存Locale的key
     */
    private static final String LOCALE_KEY = "LOCALE_KEY";

    /**
     * 获取用户设置的Locale
     *
     * @param pContext Context
     * @return Locale
     */
    public static Locale getUserLocale(Context pContext) {
        SharedPreferences _SpLocale = pContext.getSharedPreferences(LOCALE_FILE, Context.MODE_PRIVATE);
        String _LocaleJson = _SpLocale.getString(LOCALE_KEY, "");
        return jsonToLocale(_LocaleJson);
    }

    /**
     * 获取当前的Locale
     *
     * @param pContext Context
     * @return Locale
     */
    public static Locale getCurrentLocale(Context pContext) {
        Locale _Locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0有多语言设置获取顶部的语言
            _Locale = pContext.getResources().getConfiguration().getLocales().get(0);
        } else {
            _Locale = pContext.getResources().getConfiguration().locale;
        }
        return _Locale;
    }

    /**
     * 保存用户设置的Locale
     *
     * @param pContext    Context
     * @param pUserLocale Locale
     */
    public static void saveUserLocale(Context pContext, Locale pUserLocale) {
        SharedPreferences _SpLocal = pContext.getSharedPreferences(LOCALE_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor _Edit = _SpLocal.edit();
        String _LocaleJson = localeToJson(pUserLocale);
        _Edit.putString(LOCALE_KEY, _LocaleJson);
        _Edit.apply();
    }

    /**
     * Locale转成json
     *
     * @param pUserLocale UserLocale
     * @return json String
     */
    private static String localeToJson(Locale pUserLocale) {
        Gson _Gson = new Gson();
        return _Gson.toJson(pUserLocale);
    }

    /**
     * json转成Locale
     *
     * @param pLocaleJson LocaleJson
     * @return Locale
     */
    private static Locale jsonToLocale(String pLocaleJson) {
        Gson _Gson = new Gson();
        return _Gson.fromJson(pLocaleJson, Locale.class);
    }

    /**
     * 更新Locale
     *
     * @param pContext       Context
     * @param pNewUserLocale New User Locale
     */
    public static void updateLocale(Context pContext, Locale pNewUserLocale) {
        if (needUpdateLocale(pContext, pNewUserLocale)) {
            Configuration _Configuration = pContext.getResources().getConfiguration();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                _Configuration.setLocale(pNewUserLocale);
            } else {
                _Configuration.locale = pNewUserLocale;
            }
            DisplayMetrics _DisplayMetrics = pContext.getResources().getDisplayMetrics();
            pContext.getResources().updateConfiguration(_Configuration, _DisplayMetrics);
            saveUserLocale(pContext, pNewUserLocale);
        }
    }

    /**
     * 判断需不需要更新
     *
     * @param pContext       Context
     * @param pNewUserLocale New User Locale
     * @return true / false
     */
    public static boolean needUpdateLocale(Context pContext, Locale pNewUserLocale) {
        return pNewUserLocale != null && !getCurrentLocale(pContext).equals(pNewUserLocale);
    }

}

自己封装的语言设置的类

在使用时要在application  中设置语言

Locale userLocale=LocaleUtils.getUserLocale(this);
if(userLocale == null){
    userLocale = LocaleUtils.LOCALE_CHINESE;
}
LocaleUtils.updateLocale(this, userLocale);

而且为了不响应系统设置的语言的影响我们还要

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Locale _UserLocale=LocaleUtils.getUserLocale(this);
    //系统语言改变了应用保持之前设置的语言
    if (_UserLocale != null) {
        Locale.setDefault(_UserLocale);
        Configuration _Configuration = new Configuration(newConfig);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            _Configuration.setLocale(_UserLocale);
        } else {
            _Configuration.locale =_UserLocale;
        }
        getResources().updateConfiguration(_Configuration, getResources().getDisplayMetrics());
    }
}

在切换时

if (LocaleUtils.getUserLocale(mContext).equals(LocaleUtils.LOCALE_CHINESE)) {
    if (LocaleUtils.needUpdateLocale(mContext, LocaleUtils.LOCALE_ENGLISH)) {
        LocaleUtils.updateLocale(mContext, LocaleUtils.LOCALE_ENGLISH);
    }
} else if (LocaleUtils.getUserLocale(mContext).equals(LocaleUtils.LOCALE_ENGLISH)) {
    if (LocaleUtils.needUpdateLocale(mContext, LocaleUtils.LOCALE_CHINESE)) {
        LocaleUtils.updateLocale(mContext, LocaleUtils.LOCALE_CHINESE);
    }
}

restartAct();
/**
 * 重启当前Activity
 */
private void restartAct() {
    if (Build.VERSION.SDK_INT >= 11) {
        recreate();
    } else {
        finish();
        Intent _Intent = new Intent(this, LoginActivity.class);
        startActivity(_Intent);
        //清除Activity退出和进入的动画
        overridePendingTransition(0, 0);
    }
}

注意这时在8.0手机上是有问题的,还需要在(activity或者BaseActivity中添加)

@Override
protected void attachBaseContext(Context newBase) {
    Context context = languageWork(newBase);
    super.attachBaseContext(context);

}

private Context languageWork(Context context) {
    // 8.0及以上使用createConfigurationContext设置configuration
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        return updateResources(context);
    } else {
        return context;
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
private Context updateResources(Context context) {
    Resources resources = context.getResources();
    Locale locale = LocaleUtils.getUserLocale(context);;
    if (locale==null) {
        return context;
    }
    Configuration configuration = resources.getConfiguration();
    configuration.setLocale(locale);
    configuration.setLocales(new LocaleList(locale));
    return context.createConfigurationContext(configuration);
}

以上就是切换的整个过程

猜你喜欢

转载自blog.csdn.net/qq_35136577/article/details/85244281