2013-03-16 47 views
0

我希望我的應用的用戶能夠更改應用主題。例如,黑暗,光線,光線,黑暗的操作欄和設備默認。這怎麼可能,我有一個prefrences屏幕,其中有一個listpref,有四個選項(如上所示)。我如何讓用戶更改應用程序主題?用戶可以更改應用主題

謝謝

+0

是的,你可以做到。我在之前的項目中這樣做過。但是我沒有使用我的筆記本電腦,所以我無法向您展示一些示例代碼。這就是爲什麼我只是添加評論而不是答案的原因。 – TieDad 2013-03-16 11:58:27

回答

3

如果您只想使用內置主題並且您不需要對其進行自定義,那麼這很容易。

舉個例子,我將使用ListPreferece像這樣的項值:

public int getThemeId(Context context) { 
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); 
    String theme = settings.getString(context.getResources().getString(R.string.pref_theme_key), null); 

    if (theme == null || theme.equals("THEME_LIGHT")) { 
     return android.R.style.Theme_Holo_Light; 
    } else if (theme.equals("THEME_DARK")) { 
     return android.R.style.Theme_Holo; 
    } 

    // default 
    return android.R.style.Theme_Holo_Light; 
} 

之後,你應該重寫:

<string-array name="pref_theme_values" translatable="false"> 
    <item>THEME_LIGHT</item> 
    <item>THEME_DARK</item> 
</string-array> 

然後你就可以使用這種方法檢索選定值onCreate方法:

// onCreate 
this.mCurrentTheme = this.getThemeId(this); 
this.setTheme(this.mCurrentTheme); 
this.setContentView(...); // should be after the setTheme call 

onStart方法(因爲你需要儘快用戶已經從settigns頁返回刷新主題)

// onStart 
int newTheme = this.getThemeId(this); 
if(this.mCurrentTheme != newTheme) { 
    this.finish(); 
    this.startActivity(new Intent(this, this.getClass())); 
    return; 
} 

你也需要以某種方式保存活動狀態,以便應用程序顯示相同的數據後的活動重新啓動。

+0

我如何定義mCurrentTheme?結構,沒有得到它所有:/但謝謝! – 2013-03-16 13:04:52

+0

@Stian Instebo'private int mCurrentTheme;'在你的活動中。 – vorrtex 2013-03-16 13:07:31

2

下面是一個如何做到這一點的例子;

if (prefs.getBoolean("1darkTheme", false)==false){//user has selected dark theme 
     setTheme(android.R.style.Theme_Holo); 
     Toast.makeText(getApplicationContext(), "dark", Toast.LENGTH_SHORT).show(); 
    } else { 
     setTheme(android.R.style.Theme_Holo_Light); 
     Toast.makeText(getApplicationContext(), "light", Toast.LENGTH_SHORT).show(); 
    } 
    setContentView(R.layout.main); 
相關問題