更改Android应用程序的语言

时间:2017-06-01 19:10:14

标签: 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();


    }
}

2 个答案:

答案 0 :(得分:1)

您应该在SharedPreferences上存储选定的语言,并在创建的活动中查看。

答案 1 :(得分:1)

您必须在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", "");
}