在一项活动中,我执行了以下操作来更改应用的语言:
private void changeLanguage(String stringLanguage){
Locale locale = new Locale(stringLanguage);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
Intent refresh = new Intent(ActLanguage.this, ActLanguage.class);
startActivity(refresh);
finish();
}
但只有该活动会更改语言,项目包含的所有其他活动仍保留原始语言。
欢迎任何建议或意见。
答案 0 :(得分:1)
更改应用语言的一些解决方法是。
这不起作用,因为您没有拨打onConfigurationChanged()
。
这将是您的应用程序类。您可以通过调用方法来更改语言。
AppContext.getInstance().changeLanguage("en");
Intent refresh = new Intent(ActLanguage.this, ActLanguage.class);
finish();
startActivity(refresh);
和AppContext.java
类
import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import java.util.Locale;
public class AppContext extends Application {
public static final String PREFERENCE = "NYPrefsFile";
public static final String KEY_LANG = "LANG";
private static AppContext mApp = null;
@Override
public void onCreate() {
super.onCreate();
mApp = this;
setLanguage();
sp = getSharedPreferences(PREFERENCE, 0);
}
public synchronized static AppContext getInstance() {
return mApp;
}
public void setLanguage() {
String lang = getStringData(KEY_LANG);
changeLanguage(lang);
}
public String getCurrentLanguage() {
if (config == null)
config = getApplicationContext().getResources().getConfiguration();
return config.locale.getLanguage();
}
Configuration config;
public void changeLanguage(String lang) {
if (config == null)
config = getApplicationContext().getResources().getConfiguration();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());
setStringData(KEY_LANG, lang);
onConfigurationChanged(config);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private SharedPreferences sp;
public String getStringData(String pKey) {
return sp.getString(pKey, "");
}
public void setStringData(String pKey, String pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(pKey, pData);
editor.apply();
}
}
在AndroidManifest.xml
<application
android:name=".AppContext"
<强>更新强>
您将通过清除堆栈来开始您的家庭活动,以使用新语言加载所有活动。
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // call this to finish the current activity
答案 1 :(得分:0)
从Application上下文而不是Activity上下文中做。使用getApplicationContext()。
同样使用API 25中的createConfigurationContext,因为不推荐使用updateConfiguration。
答案 2 :(得分:0)
解决方案是:
Intent refresh = new Intent(ActIdioma.this, ActMAINACTIVITY.class);
refresh.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(refresh);
finish();
调用主要活动,所有其他人都会更改语言。