2016-10-02 17 views
1

トップメニューボタンからを実行しているときに、言語設定を変更できるAndroidスタジオでAndroidアプリを作成しました。すべて動作しますが、アプリを閉じるか、画面を回転させると言語はシステムにリセットされ続けます。アプリ内のの変更を永続的にするには? (私は次の行android:configChanges="locale"を持っており、削除のAndroidManifest.xmlの内側に、それは問題を解決しないことに注意してください。) を私は私のMainActivity.javaの内側に次のコードを使用しています:Android Studioで言語を永続的に変更するにはどうすればよいですか?

public void changeLanguage (String toLoad) { 
     Locale locale = new Locale(toLoad); 
     Locale.setDefault(locale); 
     Configuration config = new Configuration(); 
     config.locale= locale; 
     getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); 
     Intent intent = new Intent(MainActivity.this, MainActivity.class); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(intent); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     String languageToLoad; 
     switch (item.getItemId()) { 
      case R.id.english_menu: 
       languageToLoad = "en";    
       changeLanguage(languageToLoad); 
       return true; 
      case R.id.italian_menu:    
       languageToLoad = "it"; 
       changeLanguage(languageToLoad); 
       return true; 
      case R.id.french_menu:    
       languageToLoad = "fr"; 
       changeLanguage(languageToLoad); 
       return true;    
      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

答えて

2

保存ユーザー設定を共有設定に変更します。

/******* Create SharedPreferences *******/ 

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    Editor editor = pref.edit(); 


/**************** Storing data as KEY/VALUE pair *******************/ 


    editor.putString("lang_code", "en"); // Saving string 

    // Save the changes in SharedPreferences 
    editor.commit(); // commit changes 

アプリケーションクラスを作成し、このクラスのOnCreateの方法は、あなたの答えの@USKMobilityため

public class BaseJuiceApplication extends Application{ 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 

     Locale locale = new Locale(pref.getString("lang_code","en")); 
     Locale.setDefault(locale); 
     Configuration conf = getBaseContext().getResources().getConfiguration(); 
     config.locale= locale; 
     getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); 


    } 

} 
+0

おかげで、あなたのアプリケーションがローカル設定。私はMobile Developingを初めて使っています... ** SharedPreferences **の使い方を知るためのリンクがありますか? * MainActivity.java *の中にコードをコピーしたり、新しいファイルを作成しなければならなかったのです。 – Robb1

+0

https://developer.android.com/training/basics/data-storage/shared-preferences.html – USKMobility

関連する問題