我的应用程序用户可以从应用程序的设置中更改语言。是否可以在不影响一般语言设置的情况下更改应用程序内的语言? This question of stackoverflow对我非常有用,我已经尝试过了。更改语言后,新创建的 Activity 显示更改后的新语言,但当前 Activity 和先前创建的处于暂停状态的 Activity 不会更新。如何更新 Activity ? 我也花了很多时间试图使偏好更改立即应用但没有成功。当应用程序重新启动时,所有 Activity 都会重新创建,因此现在语言已正确更改。
android:configChanges="locale"
还添加到所有 Activity 的 list 中。并且还支持全屏。 目前我还没有在 Activity 的 onResume() 方法中做任何事情。 有没有办法刷新或更新 Activity (没有完成并重新开始)?我在 onResume() 方法中错过了一些事情吗?
最佳答案
After changing language newly created activities display with changed new language, but current activity and previously created activities which are in pause state are not updated.How to update activities ?
在 API 11 (Honeycomb) 之前,使现有 Activity 以新语言显示的最简单方法是重新启动它。这样你就不用费心自己重新加载每个资源了。
private void restartActivity() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
注册一个 OnSharedPreferenceChangeListener
,在其 onShredPreferenceChanged()
中,如果语言偏好已更改,则调用 restartActivity()
。在我的示例中,仅重新启动了 PreferenceActivity,但您应该能够通过设置标志来重新启动 Activity 恢复时的其他 Activity 。
更新(感谢@stackunderflow):从 API 11(Honeycomb)开始,您应该使用 recreate()
而不是 restartActivity()
。
public class PreferenceActivity extends android.preference.PreferenceActivity implements
OnSharedPreferenceChangeListener {
// ...
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("pref_language")) {
((Application) getApplication()).setLocale();
restartActivity();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
我有一个博客 post关于这个话题更详细,但它是中文的。完整源代码在 github:PreferenceActivity.java
关于android - 如何在应用程序内更改语言(区域设置)后刷新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049207/