NullPointerException with android.support.v7.widget.Toolbar

后端 未结 12 884
旧巷少年郎
旧巷少年郎 2021-01-07 17:53

I am currently trying to implement a navigation drawer in my app. I am having an issue with the Toolbar being null. I have done many searches online and tried many different

相关标签:
12条回答
  • 2021-01-07 18:12

    Set the id attribute in the Toolbar xml like this:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/app_bar"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" >
    </android.support.v7.widget.Toolbar>
    

    Then remove it from the include block so it looks like this:

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

    And to simplify further you could just remove the include block completely and simply insert the Toolbar directly into the xml where the include was.

    0 讨论(0)
  • 2021-01-07 18:12

    In my case , i was trying to access the Toolbar inside onAttach() method of a fragment instead of onActivityCreated() , resulting in NullPointerException.

    0 讨论(0)
  • 2021-01-07 18:13

    i was struck with the same issue and none of the answer's worked for me, i had actually forgotten to include the toolbar layout in the activity.

    <include layout="@layout/toolbar"/>
    
    0 讨论(0)
  • 2021-01-07 18:15
    <include
    android:id="@+id/toolbar"
    layout="@layout/tool_bar"/>
    

    android.support.v7.widget.Toolbar.getTitle() on a null object reference happens due to title clashes between ids of and that of the id in toolbar.xml definition . To overcome this issue remove the id in as below and latest Lollipop material design shall work fine with toolbar

    <include
    layout="@layout/tool_bar"/>
    
    0 讨论(0)
  • 2021-01-07 18:17

    Another possible cause is using a wrong layout in setContentView(R.layout.yourLayout)

    0 讨论(0)
  • 2021-01-07 18:18

    When I had this problem, I configured the layout of the activity and of the toolbar with the same id's

    0 讨论(0)
提交回复
热议问题