android主题的切换

在android中我们有时需要切换主题,这时候我们可以通过
setTheme(int);函数来设置主题。参数是主题的资源id。
setTheme函数只能在setContentView函数之前调用。
因此当你切换主题时,你需要重新启动这个activity。
代码如下所示:
MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int theme = getIntent().getIntExtra("theme", -1);
        if (theme != -1) {
            setTheme(theme);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void theme1(View view) {//按钮一
        changeTheme(R.style.theme1);
    }

    public void theme2(View view) {//按钮二
        changeTheme(R.style.theme2);
    }

    public void changeTheme(int theme) {
        overridePendingTransition(0, 0);//消除动画
        finish();
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("theme", theme);
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
}
styles.xml
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="theme1" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary1</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark1</item>
        <item name="colorAccent">@color/colorAccent1</item>
    </style>
    <style name="theme2" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary2</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark2</item>
        <item name="colorAccent">@color/colorAccent2</item>
    </style>
</resources>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值