Change app language programmatically in Android

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

    similar to the accepted answered but 2017 version and added restart (without restarting, sometimes the next Activity still renders English):

    // Inside some activity...
    private void changeDisplayLanguage(String langCode) {
    // Step 1. Change the locale in the app's configuration
        Resources res = getResources();
        android.content.res.Configuration conf = res.getConfiguration();
        conf.setLocale(currentLocale);
        createConfigurationContext(conf);
    // Step 2. IMPORTANT! you must restart the app to make sure it works 100%
        restart();
    }
    private void restart() {
        PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(getPackageName());
        ComponentName componentName = intent.getComponent();
        Intent mainIntent = IntentCompat.makeRestartActivityTask(componentName);
        mainIntent.putExtra("app_restarting", true);
        PrefUtils.putBoolean("app_restarting", true);
        startActivity(mainIntent);
        System.exit(0);
    }
    

提交回复
热议问题