Android 工具栏问题

Android Toolbar Issue

最近,我的 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(toolbar) 时工具栏仍然为空。

我的错误:

    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>

您好,您是否将工具栏包含在您的 mainActivity xml 布局中?喜欢下面的代码:

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

改变

setContentView(R.layout.content_two_player_game);

setContentView(R.layout.activity_two_player_game);

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

我遇到了同样的问题,我通过将这个主题添加到 AndroidManifest.xml 中的 activity 声明中解决了这个问题:

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

像这样:

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