如何更改应用程序语言?

时间:2016-10-29 06:18:53

标签: android localization

如何从应用设置更改应用程序的语言?

我希望我的应用支持三种语言:西班牙语,葡萄牙语和英语,并提供从我的应用设置菜单中选择语言的选项。

2 个答案:

答案 0 :(得分:1)

使用以下课程,您可以更改应用程序中的语言。

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static void onCreate(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        setLocale(context, lang);
    }

    public static void onCreate(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static void setLocale(Context context, String language) {
        persist(context, language);
        updateResources(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    private static void updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        android.content.res.Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);

    }
}

使用以下对象调用语言。

LocaleHelper.setLocale(getBaseContext(), "ar");

请在打电话后忘记刷新当前活动。希望这会对你有所帮助。

答案 1 :(得分:0)

  

实施本地化是您的解决方案

为每种语言创建单独的值文件夹,android os将根据您设备上的区域设置自动选择相应的值

请按照here步骤

进行操作

http://www.compiletimeerror.com/2014/10/android-localization-tutorial-with.html?m=1

https://www.tutorialspoint.com/android/android_localization.htm