问题
今天在写ZxingAndroid项目时,遇到这样一个问题,在项目的AndroidManifest.xml文件,添加一个MainActivity(继承自AppCompatActivity)
<activity
android:name=".activity.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
运行app的时候,报错如下:
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
分析:
以前也遇到这样的问题,成功解决了。当时是因为使用AppCompatActivity,使用的了Theme,导致的。应该使用 Theme.AppCompat。
而上面的错误,仔细检查了,并没有使用Theme,为什么还是报错?
后来在这里找到了原因:
需要明确声明使用Theme.AppCompat的主题,
解决方法:
第一种:
继承AppCompatActivity,主题必须明确使用Theme.AppCompat,不能使用Theme
在AndroidManifest.xml中添加android:theme="@style/Theme.AppCompat.Light"
更改后的代码如下:
<activity
android:name=".activity.MainActivity"
android:theme="@style/AppTheme"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
继承Activity,主题使用Theme
You need to use a Theme.AppCompat theme (or descendant) with this activity
解决错误:You need to use a Theme.AppCompat theme (or descendant) with this activity.
关注我的公众号,轻松了解和学习更多技术