应用程序在android关闭后设置为默认语言

时间:2017-09-29 08:52:22

标签: android

我正在制作一个多语言的应用程序。我提供了两种语言变化选择。语言更改正在运行,但在用户关闭应用程序后它改回默认语言。

  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.hn:
            String languageToLoad = "hi";
            Locale locale = new Locale(languageToLoad);
            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config,
                    getBaseContext().getResources().getDisplayMetrics());
            this.setContentView(R.layout.activity_main);
            Intent i = getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(getBaseContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            break;
        case R.id.eng:
            languageToLoad = "en"; // your language
            locale = new Locale(languageToLoad);
            Locale.setDefault(locale);
            config = new Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config,
                    getBaseContext().getResources().getDisplayMetrics());
            this.setContentView(R.layout.activity_main);
            Intent in = getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(getBaseContext().getPackageName());
            in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(in);
            break;

        default:

            break;
    }
    return super.onOptionsItemSelected(item);
}

3 个答案:

答案 0 :(得分:0)

您应该使用Sharedprefrences 保存您选择的语言

public void saveLanguage(String lang)
{
  SharedPreferences sharedpreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);  
  Editor editor = sharedpreferences.edit();
  editor.putString("lang", lang);
  editor.commit();
}

每次您的应用开始提取语言并应用

public String fetchLanguage()
{
  SharedPreferences sharedpreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);  
  return sharedpreferences.getString("lang", "NA");
 //NA is the default lang will be returned first time app started after choosing a language it wont . .
}

答案 1 :(得分:0)

此答案部分基于this post

基本上,您需要创建自定义Application类并调用方法来更改onCreateonConfigurationChanged中的语言,否则语言将重置为默认语言,例如,如果屏幕旋转

自定义应用

public class CustomApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        initLanguage();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initLanguage();
    }

    private void initLanguage() {
        String ul = LanguageHelper.getUserLanguage(this);
        // if null the language doesn't need to be changed as the user has not chosen one.
        if (ul != null) {
            LanguageHelper.updateLanguage(this, ul);
        }
    }
}

然后您需要告诉您的应用使用此自定义类。 在AndroidManifest添加:{/ p>下的<application

android:name=".CustomApplication"

语言助手类

public class LanguageHelper {

    private static final String GENERAL_STORAGE = "GENERAL_STORAGE";
    private static final String KEY_USER_LANGUAGE = "KEY_USER_LANGUAGE";

    /**
     * Update the app language
     *
     * @param language Language to switch to.
     */
    public static void updateLanguage(Context context, String language) {
        final Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration cfg = new Configuration(res.getConfiguration());
        cfg.locale = locale;
        res.updateConfiguration(cfg, res.getDisplayMetrics());
    }

    /**
     * Store the language selected by the user.
     * /!\ SHOULD BE CALLED WHEN THE USER CHOOSE THE LANGUAGE
     */
    public static void storeUserLanguage(Context context, String language) {
        context.getSharedPreferences(GENERAL_STORAGE, MODE_PRIVATE)
                .edit()
                .putString(KEY_USER_LANGUAGE, language)
                .apply();
    }

    /**
     * @return The stored user language or null if not found.
     */
    public static String getUserLanguage(Context context) {
        return context.getSharedPreferences(GENERAL_STORAGE, MODE_PRIVATE)
                .getString(KEY_USER_LANGUAGE, null);
    }
}

在您的用户选择语言的活动中

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    String language;
    switch (item.getItemId()) {
        case R.id.hn:
            language = "hi";
            LanguageHelper.storeUserLanguage(this, language);
            LanguageHelper.updateLanguage(this, language);

            // ... your code
            break;
        case R.id.eng:
            language = "en";
            LanguageHelper.storeUserLanguage(this, language);
            LanguageHelper.updateLanguage(this, language);

            // ... your code
            break;

        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

答案 2 :(得分:0)

试试这个。

<强> LanguageUtils

public class LanguageUtils {

/**
 * change language
 *
 * @param context
 * @param language
 */
public static void shiftLanguage(Activity context, String language) {
    if (language.equals("en")) {
        Locale.setDefault(Locale.ENGLISH);
        Configuration config = context.getResources().getConfiguration();
        config.locale = Locale.ENGLISH;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        SharedPreferenceUtils.createSP(context, "en");
    } else {
        Locale.setDefault(Locale.CHINESE);
        Configuration config = context.getResources().getConfiguration();
        config.locale = Locale.CHINESE;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        SharedPreferenceUtils.createSP(context, "zh");
    }
    context.recreate();
}

/**
 * app start setting language
 *
 * @param context
 * @param language
 */
public static void startLanguage(Context context, String language) {
    if (language.equals("zh")) {
        Locale.setDefault(Locale.CHINESE);
        Configuration config = context.getResources().getConfiguration();
        config.locale = Locale.CHINESE;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    } else {
        Locale.setDefault(Locale.ENGLISH);
        Configuration config = context.getResources().getConfiguration();
        config.locale = Locale.ENGLISH;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    }
}
}

使用

switch (item.getItemId()) {
      case R.id.hn:
           String languageToLoad = "hi";
           LanguageUtils.shiftLanguage(this, languageToLoad);
           break;
      case R.id.eng:
           languageToLoad = "en"; // your language
           LanguageUtils.shiftLanguage(this, languageToLoad);
           break;

      default:
}

并在应用程序中使用

重新启动应用时,它会设置语言。

public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    if (TextUtils.equals(SharedPreferenceUtils.getLanguage(this), "en")) {
        LanguageUtils.startLanguage(getApplicationContext(), "en");
    } else {
        LanguageUtils.startLanguage(getApplicationContext(), "zh");
    }
}

}

<强> SharedPreferenceUtils

public class SharedPreferenceUtils {

private static final String SP_NAME = "sp";
public static final String LANGUAGE = "language";


// create
public static boolean createSP(Context context, String language) {
    SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
    editor.putString(LANGUAGE, language);
    return editor.commit();
}


// get language
public static String getLanguage(Context context) {
    SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    return sp.getString(LANGUAGE, "");
}

}