在 Android 应用程序中更改按钮单击的语言

Jon*_*rry 0 java android

今天我坚持交换语言。我想在单击按钮时立即更改我的应用程序的语言。

我有两个按钮,一个用于 FR,另一个用于 ENG。我以为我可以在点击时使用另一个 strings.xml,但经过一些研究,这完全是关于位置和东西,据我所知,它根据语言电话选择了正确的语言。

是否有仅通过使用另一个 strings.xml 文件单击按钮时交换语言的解决方案?

Mit*_*vro 5

将以下类复制到您的应用程序中

public class LocaleHelper {

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

    public static void onCreate(Context context) {

        String lang;
        if(getLanguage(context).isEmpty()){
            lang = getPersistedData(context, Locale.getDefault().getLanguage());
        }else {
            lang = getLanguage(context);
        }

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

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());


    }
}
Run Code Online (Sandbox Code Playgroud)

然后如果你想改变语言,然后像这样改变它

LocaleHelper.setLocale(this,"fr") //for french;

LocaleHelper.setLocale(this,"en") //for english;
Run Code Online (Sandbox Code Playgroud)

确保你有values像法语这样的单独文件夹,values-fr并且你有两种语言的单独字符串资源。