Search code examples
javaandroidandroid-activitylocalizationlocale

Java Android: Change locale onClick in mainActivity


I want my app support 2 language, en and it, so I create a Switch to change the locale in the mainActivity. The idea is to change Locale and restart the activity passing the new language. I use API 28 to support more devices.

I tried this but it doesn't work. Sometimes change the locale but only once.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityContext = this.getApplicationContext();
        setContentView(R.layout.activity_main);

        language = findViewById(R.id.language);


        String lan = getIntent().getStringExtra("lan");
        if(lan != null) {
            if(lan.equals("ita")) {
                language.setChecked(true);
                lang = "ita";
            }else lang = "eng";
        }else if(Locale.getDefault().toString().startsWith("it")){
            language.setChecked(true);
            lang = "ita";
        }

        buttonPlay.setOnClickListener(view -> enterRoom());
        language.setOnCheckedChangeListener((compoundButton, b) -> {
            lang = b? "ita" : "eng";
            setLocale(lang);
        });
    }

    private void setLocale(String lang){
        Locale locale = new Locale(lang.substring(0, 2));
        Locale.setDefault(locale);
        Resources resources = getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        getApplicationContext().createConfigurationContext(configuration);
        Intent i = getIntent();
        i.putExtra("lan",lang);
        finish();
        startActivity(i);
    }

Solution

  • After hours of trying, I finally fixed this using updateConfiguration even though it's deprecated

    private void setLocale(String lang){
        Locale.setDefault(new Locale(lang.substring(0, 2)));
        Configuration configuration = new Configuration();
        configuration.setLocale(locale);
        getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
        Intent i = getIntent();
        i.putExtra("lan",locale);
        finish();
        startActivity(i);
    }