2012-07-10 15 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