Change app language programmatically in Android

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

    Create a class Extends Application and create a static method. Then you can call this method in all activities before setContentView().

    public class MyApp extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
    }
    
    public static void setLocaleFa (Context context){
        Locale locale = new Locale("fa"); 
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getApplicationContext().getResources().updateConfiguration(config, null);
    }
    
    public static void setLocaleEn (Context context){
        Locale locale = new Locale("en_US"); 
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getApplicationContext().getResources().updateConfiguration(config, null);
    }
    
    }
    

    Usage in activities:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApp.setLocaleFa(MainActivity.this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
    

提交回复
热议问题