Material Design之Theme样式及切换

本文介绍了Material Design的Theme样式,并展示了如何在Android应用中创建和切换两种不同主题,包括蓝色基本主题和纯黑主题。通过点击事件触发主题切换,但需要注意setTheme()必须在setContentView()之前调用。为解决这一问题,文章提出了通过重新启动Activity来实现主题切换的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说到我们的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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值