2015-12-25 77 views
0

最近,我的onCreate()方法很難將工具欄連接到我的xml文件中的工具欄。Android工具欄問題

代碼:

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

加logcat中,佈局xml文件 – piotrek1543

+0

我知道空指針異常是什麼,但我無法找到我的代碼出錯的地方。我不知道爲什麼它變爲空。一切都是(或者我認爲)設置正確。 – TheAnonymous010

回答

0

變化

setContentView(R.layout.content_two_player_game); 

setContentView(R.layout.activity_two_player_game); 

我相信content_two_player_game.xml不包含的工具欄。

1

嗨,你做你包括你的mainActivity XML佈局工具欄?如下面的代碼:

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

我有我的文件中的所有適當的包括。我以前檢查過,這不是問題。謝謝回覆。 – TheAnonymous010

0

我有同樣的問題,我在AndroidManifest.xml中添加這個主題我的活動宣言解決了這個問題:

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

這樣的:

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