2017-06-01 206 views
1

我試圖添加按鈕來更改應用程序中的語言,但 將語言更改爲阿拉伯語後, 當我退出應用程序時,它將返回英語。更改Android應用程序的語言

public class Language extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_language); 
    findViewById(R.id.BTN_ar).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      setLocale("ar"); 
     } 
    }); 
    findViewById(R.id.BTN_en).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      setLocale("en"); 
     } 
    }); 
} 

@SuppressWarnings("deprecation") 
public void setLocale(String lang) { 
    Locale myLocale = new Locale(lang); 

    DisplayMetrics dm = getResources().getDisplayMetrics(); 
    Configuration conf = getResources().getConfiguration(); 
    conf.locale = myLocale; 
    getResources().updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, MainActivity.class); 
    startActivity(refresh); 
    finish(); 


    } 
} 
+1

使用'SharedPreference' – Ibrahim

回答

0

你必須保存更改語言SharedPreference,像下面的例子:

Resources res = getApplicationContext().getResources(); 
// Change locale settings in the app. 
DisplayMetrics dm = res.getDisplayMetrics(); 
android.content.res.Configuration conf = res.getConfiguration(); 
conf.locale = new Locale(language_code); 
res.updateConfiguration(conf, dm); 
//save to shared preference 
UtilFunctions.changeLanguage(HomeActivity.this, language_code); 


public static void changeLanguage(Context context, String languageCode) { 
     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putString("lang", languageCode); 
     editor.apply(); 
} 

public static String getCurrentLanguage(Context context) { 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    return prefs.getString("lang", ""); 
} 
1

您應該將所選語言存儲在SharedPreferences上,並在創建的活動上檢查它。