异常:You need to use a Theme.AppCompat theme (or descendant) with this Activity

2,877 阅读1分钟

异常信息

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

异常分析

异常的意思是:你需要使用一个 theme.appcompat 主题(或后代)与此活动。为什么会有这种情况出现,是因为 Activity 继承的是 AppCompatActivity,如下:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

但是我使用的 appTheme 却是普通 Activity 的 Theme,所以会报错,错误提示是要求我们使用继承 theme.appcompat 的主题(或后代)。

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

异常解决

第一种方法:改变主题,使主题继承于 theme.appcompat.xxx

这是我们新建一个项目的时候,自动创建的一个 AppTheme,注意看就是继承自 Theme.AppCompat.xxx 的

<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>

第二种方法:改变类的继承父类,从 AppCompatActivity 改为 Activity。

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

——乐于分享,共同进步,欢迎留言讨论
——Treat Warnings As Errors
——Any comments greatly appreciated
——Talking is cheap, show me the code
——CSDN:blog.csdn.net/u011489043
——GitHub:github.com/selfconzrr
微信公众号【张氏文画】,不光有新鲜的 LeetCode 题解(多种思路,包教包会,开拓思维),还有经典的文章及短视频和大家分享