說到我們的Theme樣式不得不說下我們經典的一張圖
在values-v21中的style檔案中可以先建立兩個theme
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- black application theme. -->
<style name="DarkTheme" parent="Theme.AppCompat">
<item name="colorPrimary">@color/BlackColorPrimary</item>
<item name="colorPrimaryDark">@color/BlackColorPrimaryDark</item>
<item name="colorAccent">@color/BlackColorAccent</item>
</style>
關于color的代碼
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="BlackColorPrimary">#000000</color>
<color name="BlackColorPrimaryDark">#000000</color>
<color name="BlackColorAccent">#000000</color>
</resources>
可以看到是一個藍色的基本主題,和一個純黑的主題
設定了兩個主題,我們當然希望使用者在點選按鍵後能切換我們程式的主題,其實很簡單,隻要在點選事件中調用一行代碼即可,themeID即我們theme的id
setTheme(themeID);
點了你會發現木有效果,這是因為setTheme()方法需要在setContentView()方法前調用,是不是感覺這裡有點沖突的感覺,我Activity建立了我才有點選事件,怎麼才能讓activity先就知道我要設定的主題呢?
很簡單,再啟動一次自己不就行啦~
public void black(View v){
finish();//結束目前Activity
overridePendingTransition(,);//Activity切換的動畫
//重新開機自己,更換主題
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("themeID",R.style.DarkTheme);
startActivity(intent);
}
public void normal(View v){
finish();
overridePendingTransition(,);
//重新開機自己,更換主題
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("themeID",R.style.AppTheme);
startActivity(intent);
}
然後setContentView()前調用一下代碼即可
int themeID = getIntent().getIntExtra("themeID", -);
if (themeID != -){
setTheme(themeID);
}
setContentView(R.layout.activity_main);