逻辑很简单:
1 app内所有activity继承自BaseActivity或BaseActivity派生出来的子类,BaseActivity中维护了一个静态的 app Activity访问栈,在创建和销毁时会执行压栈和出栈操作,所以mLocalStack内维持的是app中正在运行的activity。
2 将app的语言环境存储在SharedPreferences中,避免app重启时修改状态不改变;在BaseActivity创建时取出语言环境字符串并初始化Activity语言环境(initLang方法)。
3 在页面切换语言时,调用BaseActivity的switchLang方法,finish当前运行的所有activity,并跳转到app主页面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
public abstract class BaseActivity extends Activity {
// activity访问栈
private static Stack<BaseActivity> mLocalStack = new Stack<BaseActivity>();
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));
}
} |