您的位置:首页 > 移动开发

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

2016-03-25 23:40 567 查看
当我的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以后的样式可以由我们自己决定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: