Android工具栏问题

时间:2015-12-25 21:44:34

标签: java android nullpointerexception toolbar

最近,我的onCreate()方法很难将工具栏连接到我的xml文件中的工具栏。

代码:

 super.onCreate(savedInstanceState);
 setContentView(R.layout.content_two_player_game);
 Toolbar toolbar = (Toolbar) findViewById(R.id.two_player_toolbar);
 setSupportActionBar(toolbar);

该应用程序在主屏幕和单人播放器屏幕中编译并运行,但是当我尝试启动双播放器屏幕时,它会崩溃。 ID是正确的,但当我尝试setSupportActionBar(工具栏)时工具栏仍然是空的。

我的错误:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.phoenixdev.yahtzee/com.***.***.TwoPlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference

activity_two_player_game.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.phoenixdev.yahtzee.TwoPlayerActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/two_player_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_two_player_game" />

</android.support.design.widget.CoordinatorLayout>

3 个答案:

答案 0 :(得分:1)

您是否在mainActivity xml布局中包含了工具栏?像下面的代码:

<include
    android:id="@+id/toolbar"
    layout="@layout/tool_bar"
    />

答案 1 :(得分:0)

更改

setContentView(R.layout.content_two_player_game);

setContentView(R.layout.activity_two_player_game);

我认为content_two_player_game.xml不包含工具栏。

答案 2 :(得分:0)

我遇到了同样的问题,我通过在AndroidManifest.xml中将此主题添加到我的活动声明中来解决它:

android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar"
像这样:

<activity
    android:name=".YourActivityName"
    android:screenOrientation="portrait"
    android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar" />