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

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

  1. <style name="AppTheme" parent="android:Theme.Material.NoActionBar">  
  2.         <!-- 5.0开始,可以在Style.xml文件中统一配置App的样式 -->  
  3.         <!-- 状态栏的颜色 -->  
  4.         <item name="colorPrimary">@color/colorPrimary</item>  
  5.         <!-- 一级文本的颜色 -->  
  6.         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  
  7.         <!-- 二级文本的颜色 -->  
  8.         <item name="colorAccent">@color/colorAccent</item>  
  9.     </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,代码如下:

  1. <resources>  
  2.   
  3.     <!-- Base application theme. -->  
  4.     <style name="AppTheme" parent="AppTheme.Base">  
  5.         <!-- Customize your theme here. -->  
  6.   
  7.     </style>  
  8.     <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">  
  9.         <item name="colorPrimary">@color/colorPrimary</item>  
  10.         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  
  11.         <item name="colorAccent">@color/colorAccent</item>  
  12.         <item name="android:windowBackground">@android:color/white</item>  
  13.     </style>  
  14. </resources>  

2、在res文件中创建values-v21文件夹,然后在此文件夹下创建styles.xml文件,代码如下:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <style name="AppTheme" parent="AppTheme.Base">  
  5.         <item name="android:colorPrimary">@color/colorPrimary</item>  
  6.         <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>  
  7.         <item name="android:colorAccent">@color/colorAccent</item>  
  8.     </style>  
  9. </resources>  
说明:values-v21文件夹中的内容是专门针对API21以上的版本所使用的配置文件,也就是说如果是API21之前的文件就是使用res/values中的styles.xml,否则使用values-v21文件夹下的styles.xml


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

原文地址:https://www.cnblogs.com/Free-Thinker/p/6042351.html