您的位置:首页 > Web前端 > CSS

Material Design之Theme样式及切换

2016-03-01 00:03 537 查看
说到我们的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(0,0);//Activity切换的动画
//重启自己,更换主题
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("themeID",R.style.DarkTheme);
startActivity(intent);
}

public void normal(View v){
finish();
overridePendingTransition(0,0);
//重启自己,更换主题
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("themeID",R.style.AppTheme);
startActivity(intent);
}


然后setContentView()前调用一下代码即可

int themeID = getIntent().getIntExtra("themeID", -1);
if (themeID != -1){
setTheme(themeID);
}

setContentView(R.layout.activity_main);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息