滑动标签 - NullPointerException - Toolbar.getTitle()

时间:2015-06-20 16:28:10

标签: android xml

我正在尝试在我的应用程序中实现制表符。问题是Toolbar为null。我正在学习本教程:http://android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html

错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

    <com.android4devs.slidingtab.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/colorPrimary"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"

        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        ></android.support.v4.view.ViewPager>

</LinearLayout>

MainActivity.java

toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar); //error

tool_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:elevation="2dp"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Light" />

2 个答案:

答案 0 :(得分:1)

显然这个错误是因为我忘记回到setContentView(R.layout.activity_main);

答案 1 :(得分:0)

我没有尝试,但我认为从include标记中删除android:id="@+id/tool_bar"并将其添加到android.support.v7.widget.Toolbar标记将解决问题。