【发布时间】:2016-11-04 01:15:30
【问题描述】:
我收到一个错误提示
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity...
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference at com.myapp.contactList.MainPage.onCreate(MainPage.java:41)
我查找了几个与此类似的堆栈溢出问题并尝试了所有解决方案,但仍然遇到此问题。以下是我的代码:
MainPage.java
public class MainPage extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
android.support.v7.app.ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true); // I'M GETTING THE ERROR HERE AT THIS LINE
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#51c2f2")));
ab.setDisplayUseLogoEnabled(true);
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.contactList">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainPage"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
styles.xml
<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>
activity_main_page.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.myapp.contactList.MainPage">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main_page" />
</android.support.design.widget.CoordinatorLayout>
【问题讨论】:
-
您确定您使用的主题吗?错误提示“使用 AppCompat 主题”但在发布的代码中您使用的是应用程序兼容主题
-
我不确定我是否理解您的评论。错误告诉我使用 AppCompat 主题,而我正在使用 AppCompat 主题,那么为什么会抛出该错误?
-
@someonenew 检查我的答案
-
这和你用的一样吗?
-
@someonenew 你试过我的解决方案了吗?
标签: java android xml android-studio nullpointerexception