Change app language programmatically in Android

前端 未结 30 3052
面向向阳花
面向向阳花 2020-11-21 04:34

Is it possible to change the language of an app programmatically while still using Android resources?

If not, is it possible to request a resource in an specific lan

相关标签:
30条回答
  • 2020-11-21 05:07

    According to this article. You will need to download LocaleHelper.java referenced in that article.

    1. Create MyApplication class that will extends Application
    2. Override attachBaseContext() to update language.
    3. Register this class in manifest.

      public class MyApplication extends Application {
         @Override
         protected void attachBaseContext(Context base) {
          super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
         }
      }
      
      <application
           android:name="com.package.MyApplication"
           .../>
      
    4. Create BaseActivity and override onAttach() to update language. Needed for Android 6+

      public class BaseActivity extends Activity {
        @Override
        protected void attachBaseContext(Context base) {
          super.attachBaseContext(LocaleHelper.onAttach(base));
        }
      }
      
    5. Make all activities on your app extends from BaseActivity.

      public class LocaleHelper {
      
      private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
      
      public static Context onAttach(Context context) {
          String lang = getPersistedData(context, Locale.getDefault().getLanguage());
          return setLocale(context, lang);
      }
      
      public static Context onAttach(Context context, String defaultLanguage) {
          String lang = getPersistedData(context, defaultLanguage);
          return setLocale(context, lang);
      }
      
      public static String getLanguage(Context context) {
          return getPersistedData(context, Locale.getDefault().getLanguage());
      }
      
      public static Context setLocale(Context context, String language) {
          persist(context, language);
      
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
              return updateResources(context, language);
          }
      
          return updateResourcesLegacy(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();
      }
      
      @TargetApi(Build.VERSION_CODES.N)
      private static Context updateResources(Context context, String language) {
          Locale locale = new Locale(language);
          Locale.setDefault(locale);
      
          Configuration configuration = context.getResources().getConfiguration();
          configuration.setLocale(locale);
          configuration.setLayoutDirection(locale);
      
          return context.createConfigurationContext(configuration);
      }
      
      @SuppressWarnings("deprecation")
      private static Context updateResourcesLegacy(Context context, String language) {
          Locale locale = new Locale(language);
          Locale.setDefault(locale);
      
          Resources resources = context.getResources();
      
          Configuration configuration = resources.getConfiguration();
          configuration.locale = locale;
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
              configuration.setLayoutDirection(locale);
          }
      
          resources.updateConfiguration(configuration, resources.getDisplayMetrics());
      
          return context;
      }
      }
      
    0 讨论(0)
  • 2020-11-21 05:07

    For Android 7.0 Nougat (and lower) follow this article:

    Change Language Programatically in Android

    Old answer
    This include RTL/LTR support:

    public static void changeLocale(Context context, Locale locale) {
        Configuration conf = context.getResources().getConfiguration();
        conf.locale = locale;
        Locale.setDefault(locale);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
           conf.setLayoutDirection(conf.locale);
        }
    
        context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
    }
    
    0 讨论(0)
  • 2020-11-21 05:07

    Add LocaleHelper class

    public class LocaleHelper{ 
    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }
    
    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }
    
    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }
    public static Context setLocale(Context context, String language) {
        persist(context, language);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }
    
        return updateResourcesLegacy(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();
    }
    
    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
    
        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);
    
        return context.createConfigurationContext(configuration);
    }
    
    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
    
        Resources resources = context.getResources();
    
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }
    
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    
        return context;
    }
    }
    

    In Activity or Fragment

    Context context = LocaleHelper.setLocale(this, App.getSharedPre().getLanguage());
    Resource resources = context.getResources();
    

    Now SetText on every text

    TextView tv = findViewById(R.id.tv);
    tv.setText(resources.getString(R.string.tv));
    
    0 讨论(0)
  • 2020-11-21 05:08

    I was facing the same issue. On GitHub I found the Android-LocalizationActivity library.

    This library makes it very simple to change the language of your app at runtime, as you can see in the code sample below. A sample project including the sample code below and more information can be found at the github page.

    The LocalizationActivity extends AppCompatActivity, so you can also use it when you are using Fragments.

    public class MainActivity extends LocalizationActivity implements View.OnClickListener {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_simple);
    
            findViewById(R.id.btn_th).setOnClickListener(this);
            findViewById(R.id.btn_en).setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_en) {
                setLanguage("en");
            } else if (id == R.id.btn_th) {
                setLanguage("th");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:08

    At first create multi string.xml for different languages; then use this block of code in onCreate() method:

    super.onCreate(savedInstanceState);
    String languageToLoad  = "fr"; // change your language here
    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.main);
    
    0 讨论(0)
  • 2020-11-21 05:08

    Alex Volovoy answer only works for me if it's in onCreate method of the activity.

    The answer that works in all the methods is in another thread

    Change language programmatically in Android

    Here is the adaptation of the code

    
    
        Resources standardResources = getBaseContext().getResources();
    
        AssetManager assets = standardResources.getAssets();
    
        DisplayMetrics metrics = standardResources.getDisplayMetrics();
    
        Configuration config = new Configuration(standardResources.getConfiguration());
    
        config.locale = new Locale(languageToLoad);
    
        Resources defaultResources = new Resources(assets, metrics, config);
    
    

    Hope that it helps.

    0 讨论(0)
提交回复
热议问题