2016-09-22 50 views
1

我想在所有活動中更改語言。是否有任何簡單的方法來改變語言,而不使用字符串資源。我嘗試過類似於下面的代碼,但不行。任何人都可以通過簡單的方式幫助我改變所有活動中的語言嗎?如何在android中更改所有活動的languge

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

     public void onItemSelected(AdapterView arg0, View arg1, 
            int arg2, long arg3) { 
      Configuration config = new Configuration(); 
      switch (arg2) { 
       case 0: 
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LocalizationUpdaterActivity.this); 
        preferences.edit().putString("lang", "ar").commit(); 
        break; 
       case 1: 

        break; 

       default: 
        config.locale = Locale.TAIWAN; 
        break; 
      } 

     } 

     public void onNothingSelected(AdapterView arg0) { 
      // TODO Auto-generated method stub 

     } 
    }); 

施藥代碼:

public class MainApplication extends Application { 
    @Override 
    public void onCreate() { 
     super.onCreate(); 
     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 
     String lang = preferences.getString("lang", "en"); 
     Locale locale = new Locale(lang); 
     Locale.setDefault(locale); 
     Configuration config = new Configuration(); 
     config.locale = locale; 
     getBaseContext().getResources().updateConfiguration(config, 
       getBaseContext().getResources().getDisplayMetrics()); 
    } 
} 

回答

0

基本上你的代碼是正確的。

以下代碼有效。檢查你是否沒有遺漏任何東西。 我猜你的應用程序代碼沒有執行,或者你的字符串翻譯不可用。


工作示例:


應用:

@Override 
public void onCreate() { 
    super.onCreate(); 
    setResourceLocale(new Locale("en")); 
} 

private void setResourceLocale(Locale locale){ 
    if(Build.VERSION.SDK_INT >= 17){ 
     getBaseContext().getResources().getConfiguration().setLocale(locale); 
    }else{ 
     Configuration config = getResources().getConfiguration(); 
     config.locale = locale; 
     getBaseContext().getResources().updateConfiguration(config,getResources().getDisplayMetrics()); 
    } 
} 

活動:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Log.i(TAG, getString(android.R.string.no)); 
} 

的AndroidManifest.xml:

確保您添加您的自定義應用程序類!

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme" 
    android:name=".MainApplication" 
    > 

    <activity android:name=".MainActivity" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

增加:

使用帶有國家代碼的語言使用:

new Locale("de","DE") 

退房this SO回答正確的代碼。

+0

有沒有什麼方法可以在沒有字符串轉換的情況下改變語言 –

+0

不,但是android提供了一些可以使用的轉換字符串。 – FlanschiFox