逻辑很简单:
1 app内所有activity继承自BaseActivity或BaseActivity派生出来的子类,BaseActivity中维护了一个静态的app Activity访问栈,在创建和销毁时会执行压栈和出栈操作,所以mLocalStack内维持的是app中正在运行的activity。
2 将app的语言环境存储在SharedPreferences中,避免app重启时修改状态不改变;在BaseActivity创建时取出语言环境字符串并初始化Activity语言环境(initLang方法)。
3 在页面切换语言时,调用BaseActivity的switchLang方法,finish当前运行的所有activity,并跳转到app主页面。
public abstract class BaseActivity extends Activity {
// activity访问栈
private static Stack mLocalStack = new Stack();
protected BaseActivity mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
// 压栈
mLocalStack.add(this);
initLang();
}
@Override
protected void onDestroy() {
// 出栈
mLocalStack.remove(this);
super.onDestroy();
}
private void initLang() {
Resources res = getResources();
Configuration config = res.getConfiguration();
Locale locale = Locale.getDefault();
String langStr = "";
//TODO 获取Sharedpreferences中存储的app语言环境
if("zh".equals(langStr)){
locale = Locale.CHINA;
}else if("en".equals(langStr)){
locale = Locale.ENGLISH;
}else if{
//.....
}
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
}
protected void switchLang(String newLang){
//TODO 更新Sharedpreferences中存储的app语言环境
// finish app内存中的所有activity
while (0 != mLocalStack.size()) {
mLocalStack.pop().finish();
}
// 跳转到app首页
startActivity(MainActivity.class);
}
public void startActivity(Class extends BaseActivity> cls) {
startActivity(new Intent(this, cls));
}
}