2012-07-10 54 views
9

可能重复:
How to change current Theme at runtime in Android变化并在运行时应用主题的Android

我有一个Android应用程序,我允许用户在运行时主题之间切换。切换主题是容易的,但我the theme isn't applied until the activity is recreated.发现了一种apply the theme to current activity但如果用户按下后退按钮前面的屏幕仍然有旧的主题。我怎样才能改变这些活动的主题?支持它的应用实例:Tasks Free

回答

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() 
     } 
    } 
} 
+0

你好警长,我想从您知道是否有可能是任何解决方案,我从网上得到的颜色代码,并根据我可以改变我的所有按钮运行时的颜色而不去所有的特定按键和应用背景颜色,莫不是任何解决方案使用主题或风格?请分享您的任何建议。 – MKJParekh 2014-03-20 07:54:23

+0

你有无限的色彩吗?或只是有限的一套颜色? – 2014-03-21 15:15:30

+0

我做有限的20种颜色的发言权,但那些20会从服务器上下载的,因此可能会有所不同,从一个时间到另一个,总之颜色是15-20左右(不是修复),以及那些颜色代码也没有解决。其中一个用户已经建议使用CustomViews http://stackoverflow.com/questions/22529646/android-app-apply-color-theme-dynamically-at-runtime – MKJParekh 2014-03-22 04:40:24

5

在运行时动态,在活动的onCreate调用setTheme()()方法,然后调用setContentView()。要更改主题,只需重新启动活动即可。

请参阅this file..!

也希望看到thisthis ... 希望这有助于...!

+1

重新启动活动适用于当前的一个,但是,当用户点击回按钮以前的活动仍旧有旧主题。这是因为onCreate在用户返回时不被调用,所以我无法设置主题。 – Giorgi 2012-07-13 09:10:26

+0

你想设置主题永久性,然后像动态壁纸一样使一个应用程序,然后在设置你可以添加不同的风格..! @Giorgi – 2012-07-13 09:42:37

+3

这并不回答这个问题。重新启动活动适用于当前显示的活动,但如何在用户点击后将其应用于其他活动? – Giorgi 2012-07-19 16:09:03