我有一个Android应用程序,我允许用户在运行时切换主题。切换主题很简单但是the theme isn't applied until the activity is recreated.我找到了apply the theme to current activity的方法,但是如果用户按下后退按钮,之前的屏幕仍然具有旧主题。如何更改这些活动的主题?支持它的应用示例:Tasks Free
答案 0 :(得分:5)
在运行时动态调用活动的onCreate()方法中的setTheme(),然后再调用setContentView()。要更改主题,只需重新启动活动即可。
请参阅this file..!
答案 1 :(得分:4)
我想是一个暗示:
在finish();
致电之前
setResult(AnIntegerThatNotifiesThePreviousActivitiesToChangeTheme);
现在,在所有活动中,实施onActivityResult
protected void onActivityResult(int request, int result, Intent data) {
if(result == AnIntegerThatNotifiesThePreviousActivitiesToChangeTheme)
{
//update the current theme
}
}
另一种解决方案(更好):
实现一个保存主题的类:
public class CurrentThemeHolder {
private CurrentThemeHolder() {
}
private static instance;
public static getInstance() {
if(instance == null)
return new CurrentThemeHolder();
else
return instance;
}
private int mTheme; //identifier of the theme
public getTheme() {
return mTheme;
}
public setTheme(int newTheme){
mTheme = newTheme;
}
}
现在让所有你的活动扩展这个ThemeActivity:
public class ThemeActivity extends Activity {
private int mTheme;
protected void onResume() {
if(mTheme != CurrentThemeHolder.getInstance().getTheme()) {
//do what you should do to set the theme
mTheme = CurrentThemeHolder.getInstance().getTheme();
//everytime you set the theme save it
//this maybe should be done in onCreate()
}
}
}