You need to use a Theme.AppCompat theme (or descendant) with this activity解决方法

当我的MainActivity继承自v7包中的ActionBarActivity或者AppCompatActivity时,如果在style.xml文件中指定MainActivity所使用的样式如下:

<style name="AppTheme" parent="android:Theme.Material.NoActionBar">
        <!-- 5.0开始,可以在Style.xml文件中统一配置App的样式 -->
        <!-- 状态栏的颜色 -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <!-- 一级文本的颜色 -->
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <!-- 二级文本的颜色 -->
        <item name="colorAccent">@color/colorAccent</item>
    </style>

会报如下错误:

java.lang.IllegalStateException:You need to use a Theme.AppCompat theme(or descendatn) with this activity

那么如何解决这个问题呢?网上很多人生说将MainActivity改为继承自Activity即可,但是这样的话就早晨无法兼容老版本的样式,或者说是无法再5.0之前的版本实现MaterialDesign的效果,那么该如何正确的修改呢? 

解决步骤如下:

1、res/styles.xml文件中重新添加一个style样式AppTheme.Base,然后将AppTheme继承自AppTheme.Base,代码如下:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
        <!-- Customize your theme here. -->

    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@android:color/white</item>
    </style>
</resources>

2、在res文件中创建values-v21文件夹,然后在此文件夹下创建styles.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:colorPrimary">@color/colorPrimary</item>
        <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="android:colorAccent">@color/colorAccent</item>
    </style>
</resources>
说明:values-v21文件夹中的内容是专门针对API21以上的版本所使用的配置文件,也就是说如果是API21之前的文件就是使用res/values中的styles.xml,否则使用values-v21文件夹下的styles.xml


通过以上两步,就可以轻松实现MainActivity还是继承自AppCompatActivity,也就是说可以将Material Design的效果运行在API21之前版本的手机上,并且API21之前的样式和API21以后的样式可以由我们自己决定

  • 22
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值