アクティビティで、アプリの言語を変更するために次のことを行いました。
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();
}
ただし、そのアクティビティのみが言語を変更し、プロジェクトに含まれる他のすべてのアクティビティは元の言語のままになります。
任意の提案やコメントを歓迎します。
アプリの言語を変更するためのいくつかの回避策は次のとおりです。
を呼び出さなかったため、これは機能しません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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加