4

I want to change the language of my options menu. This code works in all my activity excepts menu.

public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
        case R.id.ingles:
            mLocale = new Locale("en");
            Locale.setDefault(mLocale); 
            config = getBaseContext().getResources().getConfiguration(); 
            if (!config.locale.equals(mLocale)) { 
                config.locale = mLocale; 
                getBaseContext().getResources().updateConfiguration(config, null); 
            }
            setContentView(R.layout.main);
            break;

        case R.id.euskera:
            mLocale = new Locale("eu");
            Locale.setDefault(mLocale); 
            config = getBaseContext().getResources().getConfiguration(); 
            if (!config.locale.equals(mLocale)) { 
                config.locale = mLocale; 
                getBaseContext().getResources().updateConfiguration(config, null); 
            }
            setContentView(R.layout.main);
            break;
    }
    return super.onOptionsItemSelected(item);
}

why? I tried with onPrepareOptionsMenu but it creates additional menus

public boolean onPrepareOptionsMenu(Menu menu) {

    if(config.equals(this.getBaseContext().getResources().getConfiguration())){
        MenuInflater inflater = this.getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    return false;

}
Loyalar
  • 2,131
  • 4
  • 24
  • 44
monchyrcg
  • 372
  • 1
  • 6
  • 16

1 Answers1

1

Better to put the menu title string in Values string.xml and set in menu.xml from there

like

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"

          android:title="@string/new_game"
          />

</menu>

and if you want to change it at run time refer this

Change language programmatically in Android

Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
  • I do that, i've all my strings in string.xml and I use these strings like you. I have three folder values, values-es,values-ca with strings in their languages. – monchyrcg Jun 15 '12 at 11:06
  • I have another problem, when i change the languaje my botons dont works. What should i do? Edit this ask or create another. – monchyrcg Jun 15 '12 at 11:50
  • if this solution works for you just accept this answer and better to make other as looks not linked with menu ...... :) – Dheeresh Singh Jun 15 '12 at 11:52
  • Your buttons not work because you just setContentView(R.layout.main) again. You should init button one more times. Ex: Button btn = (Button) findViewById(R.d.btnExample)... – ChickenVN91 Dec 26 '15 at 07:36