Home > Net >  Multilanguage android app doesn't update the language when it is started
Multilanguage android app doesn't update the language when it is started

Time:04-11

i've this method that it should update the language of the app. When i start the app and set italian language, the app set correctly the language selected. But when i close the app and restart it the language selected isn't mantained but in the TextView the language is correctly updated. the problema is that it isn't mantained after tha the app is restarted.

Who can help me? thanks anticipately

private TextView language_dialog;
private Context context;
private int lang_selected;

@Override
    protected void onStart() {
        super.onStart();

        if (LocaleHelper.getLanguage(getApplicationContext()).equalsIgnoreCase("it")) {
            context = LocaleHelper.setLocale(this, "it");
            lang_selected = 0;
            language_dialog.setText("Italiano");
        } else if (LocaleHelper.getLanguage(getApplicationContext()).equalsIgnoreCase("en")) {
            context = LocaleHelper.setLocale(this, "en");
            lang_selected = 1;
            language_dialog.setText("English");
        }



        language_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //lista delle lingue disponibili
                final String[] language = {"Italiano", "Inglese"};

                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
                dialogBuilder.setTitle("Seleziona una lingua...")
                        .setSingleChoiceItems(language, lang_selected, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //language_dialog.setText(language[i]);

                                if (language[i].equals("Italiano")) {
                                    LocaleHelper.setLocale(LoginActivity.this, "it");
                                    lang_selected = 0;
                                }
                                if (language[i].equals("Inglese")) {
                                    LocaleHelper.setLocale(LoginActivity.this, "en");
                                    lang_selected = 1;
                                }
                            }
                        })
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                recreate();
                            }
                        });
                dialogBuilder.create().show();
            }
        });


    }

CodePudding user response:

Use below code for changing the language of the app.

public void setLocale(String languageCode) { 
        Locale myLocale = new Locale(languageCode); 
        Resources res = getResources(); 
        DisplayMetrics dm = res.getDisplayMetrics(); 
        Configuration conf = res.getConfiguration(); 
        conf.locale = myLocale; 
        res.updateConfiguration(conf, dm); 
        Intent refresh = new Intent(this, MainActivity.class); 
        finish();
        startActivity(refresh); 
    }

Initially if user click on change language button you have to save the language code("in" or "it") in shared preference.If user close the app and open again then get the shared preference in splash screen and pass the language code in above method.

CodePudding user response:

Use the Following code it will help you with language change. Here is full-example

LocaleHelper.kt

object LocaleHelper {
    fun setLocale(context: Context): Context? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            updateResources(context, getLanguageCode(context))
        } else updateResourcesLegacy(context, getLanguageCode(context))
    }


    @TargetApi(Build.VERSION_CODES.N)
    private fun updateResources(context: Context, language: String): Context? {
        val locale = Locale(language)
        Locale.setDefault(locale)
        val configuration: Configuration = context.resources.configuration
        configuration.setLocale(locale)
        configuration.setLayoutDirection(locale)
        return context.createConfigurationContext(configuration)
    }

    private fun updateResourcesLegacy(context: Context, language: String): Context{
        val locale = Locale(language)
        Locale.setDefault(locale)
        val resources: Resources = context.resources
        val configuration: Configuration = resources.configuration
        configuration.locale = locale
        configuration.setLayoutDirection(locale)
        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }
}

SharedPreferencesUtils.kt

object SharedPreferencesUtils {

    fun getLanguageCode(mContext: Context):String{
        val sharedPreferences: SharedPreferences=mContext.getSharedPreferences("languageCodePrefs", Context.MODE_PRIVATE)
        return sharedPreferences.getString("languageCodeValue", "en")!!
    }

    fun setLanguageCode(mContext: Context, code: String){
        val sharedPreferences: SharedPreferences=mContext.getSharedPreferences("languageCodePrefs", Context.MODE_PRIVATE)
        val sharedPreferencesEditor: SharedPreferences.Editor  = sharedPreferences.edit()
        sharedPreferencesEditor.putString("languageCodeValue", code)
        sharedPreferencesEditor.apply()
    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

       // set the following line of code in your language button click listener
        setLanguageCode(this, "it")
        recreate()

    }

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(LocaleHelper.setLocale(newBase!!))
    }

}
  • Related