Change app language programmatically in Android

前端 未结 30 3058
面向向阳花
面向向阳花 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:20

    I know it's late to answer but i found this article here . Which explains the whole process very well and provides you a well structured code.

    Locale Helper class:

    import android.annotation.TargetApi;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.res.Configuration;
    import android.content.res.Resources;
    import android.os.Build;
    import android.preference.PreferenceManager;
    
    import java.util.Locale;
    
    /**
     * This class is used to change your application locale and persist this change for the next time
     * that your app is going to be used.
     * <p/>
     * You can also change the locale of your application on the fly by using the setLocale method.
     * <p/>
     * Created by gunhansancar on 07/10/15.
     */
    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;
        }
    }
    

    You need to override attachBaseContext and call LocaleHelper.onAttach() to initialize the locale settings in your application.

    import android.app.Application;
    import android.content.Context;
    
    import com.gunhansancar.changelanguageexample.helper.LocaleHelper;
    
    public class MainApplication extends Application {
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
        }
    }
    

    All you have to do is to add

    LocaleHelper.onCreate(this, "en");
    

    wherever you want to change the locale.

    0 讨论(0)
  • 2020-11-21 05:22

    The only solution that fully works for me is a combination of Alex Volovoy's code with application restart mechanism:

    void restartApplication() {
        Intent i = new Intent(MainTabActivity.context, MagicAppRestart.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MainTabActivity.context.startActivity(i);
    }
    
    
    /** This activity shows nothing; instead, it restarts the android process */
    public class MagicAppRestart extends Activity {
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            finish();
        }
    
        protected void onResume() {
            super.onResume();
            startActivityForResult(new Intent(this, MainTabActivity.class), 0);         
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:23

    If you want to mantain the language changed over all your app you have to do two things.

    First, create a base Activity and make all your activities extend from this:

    public class BaseActivity extends AppCompatActivity {
    
        private Locale mCurrentLocale;
    
        @Override
        protected void onStart() {
            super.onStart();
    
            mCurrentLocale = getResources().getConfiguration().locale;
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            Locale locale = getLocale(this);
    
            if (!locale.equals(mCurrentLocale)) {
    
                mCurrentLocale = locale;
                recreate();
            }
        }
    
        public static Locale getLocale(Context context){
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    
            String lang = sharedPreferences.getString("language", "en");
            switch (lang) {
                case "English":
                    lang = "en";
                    break;
                case "Spanish":
                    lang = "es";
                    break;
            }
            return new Locale(lang);
        }
    }
    

    Note that I save the new language in a sharedPreference.

    Second, create an extension of Application like this:

        public class App extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            setLocale();
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            setLocale();
        }
    
        private void setLocale() {
    
            final Resources resources = getResources();
            final Configuration configuration = resources.getConfiguration();
            final Locale locale = getLocale(this);
            if (!configuration.locale.equals(locale)) {
                configuration.setLocale(locale);
                resources.updateConfiguration(configuration, null);
            }
        }
    }
    

    Note that getLocale() it's the same as above.

    That's all! I hope this can help somebody.

    0 讨论(0)
  • 2020-11-21 05:23

    Take note that this solution using updateConfiguration will not be working anymore with the Android M release coming in a few weeks. The new way to do this is now using the applyOverrideConfigurationmethod from ContextThemeWrapper see API doc

    You can find my full solution here since I faced the problem myself: https://stackoverflow.com/a/31787201/2776572

    0 讨论(0)
  • 2020-11-21 05:24

    Time for a due update.

    First off, the deprecated list with the API in which it was deprecated:

    • configuration.locale (API 17)
    • updateConfiguration(configuration, displaymetrics) (API 17)

    The thing no question answered recently has gotten right is the usage of the new method.

    createConfigurationContext is the new method for updateConfiguration.

    Some have used it standalone like this:

    Configuration overrideConfiguration = ctx.getResources().getConfiguration();
    Locale locale = new Locale("en_US");
    overrideConfiguration.setLocale(locale);
    createConfigurationContext(overrideConfiguration);
    

    ... but that doesn't work. Why? The method returns a context, which then is used to handle Strings.xml translations and other localized resources (images, layouts, whatever).

    The proper usage is like this:

    Configuration overrideConfiguration = ctx.getResources().getConfiguration();
    Locale locale = new Locale("en_US");
    overrideConfiguration.setLocale(locale);
    //the configuration can be used for other stuff as well
    Context context  = createConfigurationContext(overrideConfiguration);
    Resources resources = context.getResources();
    

    If you just copy-pasted that into your IDE, you may see a warning that the API requires you targeting API 17 or above. This can be worked around by putting it in a method and adding the annotation @TargetApi(17)

    But wait. What about the older API's?

    You need to create another method using updateConfiguration without the TargetApi annotation.

    Resources res = YourApplication.getInstance().getResources();
    // Change locale settings in the app.
    DisplayMetrics dm = res.getDisplayMetrics();
    android.content.res.Configuration conf = res.getConfiguration();
    conf.locale = new Locale("th");
    res.updateConfiguration(conf, dm);
    

    You don't need to return a context here.

    Now, managing these can be difficult. In API 17+ you need the context created (or the resources from the context created) to get the appropriate resources based on localization. How do you handle this?

    Well, this is the way I do it:

    /**
     * Full locale list: https://stackoverflow.com/questions/7973023/what-is-the-list-of-supported-languages-locales-on-android
     * @param lang language code (e.g. en_US)
     * @return the context
     * PLEASE READ: This method can be changed for usage outside an Activity. Simply add a COntext to the arguments
     */
    public Context setLanguage(String lang/*, Context c*/){
        Context c = AndroidLauncher.this;//remove if the context argument is passed. This is a utility line, can be removed totally by replacing calls to c with the activity (if argument Context isn't passed)
        int API = Build.VERSION.SDK_INT;
        if(API >= 17){
            return setLanguage17(lang, c);
        }else{
            return setLanguageLegacy(lang, c);
        }
    }
    
    /**
     * Set language for API 17
     * @param lang
     * @param c
     * @return
     */
    @TargetApi(17)
    public Context setLanguage17(String lang, Context c){
        Configuration overrideConfiguration = c.getResources().getConfiguration();
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);
        overrideConfiguration.setLocale(locale);
        //the configuration can be used for other stuff as well
        Context context  = createConfigurationContext(overrideConfiguration);//"local variable is redundant" if the below line is uncommented, it is needed
        //Resources resources = context.getResources();//If you want to pass the resources instead of a Context, uncomment this line and put it somewhere useful
        return context;
    }
    
    public Context setLanguageLegacy(String lang, Context c){
        Resources res = c.getResources();
        // Change locale settings in the app.
        DisplayMetrics dm = res.getDisplayMetrics();//Utility line
        android.content.res.Configuration conf = res.getConfiguration();
    
        conf.locale = new Locale(lang);//setLocale requires API 17+ - just like createConfigurationContext
        Locale.setDefault(conf.locale);
        res.updateConfiguration(conf, dm);
    
        //Using this method you don't need to modify the Context itself. Setting it at the start of the app is enough. As you
        //target both API's though, you want to return the context as you have no clue what is called. Now you can use the Context
        //supplied for both things
        return c;
    }
    

    This code works by having one method that makes calls to the appropriate method based on what API. This is something I have done with a lot of different deprecated calls (including Html.fromHtml). You have one method that takes in the arguments needed, which then splits it into one of two (or three or more) methods and returns the appropriate result based on API level. It is flexible as you do't have to check multiple times, the "entry" method does it for you. The entry-method here is setLanguage

    PLEASE READ THIS BEFORE USING IT

    You need to use the Context returned when you get resources. Why? I have seen other answers here who use createConfigurationContext and doesn't use the context it returns. To get it to work like that, updateConfiguration has to be called. Which is deprecated. Use the context returned by the method to get resources.

    Example usage:

    Constructor or somewhere similar:

    ctx = getLanguage(lang);//lang is loaded or generated. How you get the String lang is not something this answer handles (nor will handle in the future)
    

    And then, whereever you want to get resources you do:

    String fromResources = ctx.getString(R.string.helloworld);
    

    Using any other context will (in theory) break this.

    AFAIK you still have to use an activity context to show dialogs or Toasts. for that you can use an instance of an activity (if you are outside)


    And finally, use recreate() on the activity to refresh the content. Shortcut to not have to create an intent to refresh.

    0 讨论(0)
  • 2020-11-21 05:25

    I am changed for German language for my app start itself.

    Here is my correct code. Anyone want use this same for me.. (How to change language in android programmatically)

    my code:

    Configuration config ; // variable declaration in globally
    
    // this part is given inside onCreate Method starting and before setContentView()
    
    public void onCreate(Bundle icic) 
    {
        super.onCreate(icic);
        config = new Configuration(getResources().getConfiguration());
        config.locale = Locale.GERMAN ;
        getResources().updateConfiguration(config,getResources().getDisplayMetrics());
    
        setContentView(R.layout.newdesign);
    }
    
    0 讨论(0)
提交回复
热议问题