工具栏 - findViewbyID返回null

dii*_*iz_ 9 android toolbar android-5.0-lollipop

为什么我无法找到我Toolbar的布局?

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
}
Run Code Online (Sandbox Code Playgroud)

之后,工具栏仍为空.

activity_man.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    tools.context=".PlayerActivity">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar"/>
    <ImageView
        android:id="@+id/background_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>
        : (goes on)
Run Code Online (Sandbox Code Playgroud)

编辑:

toolbar.xml:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"/>
Run Code Online (Sandbox Code Playgroud)

谢谢!

kun*_*l.c 5

您的代码运行良好,您可能没有禁用默认操作栏:

在styles.xml 中更改以下内容以删除操作栏

<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">

    <item name="windowActionBar">false</item>

</style>
Run Code Online (Sandbox Code Playgroud)

将工具栏放在前面使用 toolbar.bringToFront();