2012-06-15 39 views
1

我想更改我的選項菜單的語言。此代碼適用於除菜單之外的所有活動。如何更改選項菜單的語言?

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); 
} 

爲什麼?我試着用onPrepareOptionsMenu但它創造更多的菜單

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; 

} 

回答

1

更好地把在價值string.xml菜單標題字符串,並從那裏menu.xml設置

<?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> 

,如果你想改變它在運行時請參考此

Change language programmatically in Android

+0

我這樣做,我已經把所有的字符串放在了string.xml中,並且使用了像你這樣的字符串。我有三個文件夾值,值爲es,值爲ca,並且包含語言中的字符串。 – monchyrcg

+0

我有另一個問題,當我改變languaje我botons不工作。我該怎麼辦?編輯此問題或創建另一個問題。 – monchyrcg

+0

如果這個解決方案適合你只是接受這個答案,並更好地使其他看起來沒有鏈接菜單...... :) –