Toolbar - findViewbyID returning null

萝らか妹 提交于 2019-12-23 07:59:17

问题


Why am I unable to find my Toolbar in my layout?

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
}

After that, toolbar is still null.

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)

EDIT:

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"/>

Thanks!


回答1:


Your code is working fine you may not have disable default actionbar:

Change the following in styles.xml to remove action bar

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

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

</style>

Bring toolbar to front using toolbar.bringToFront();



来源:https://stackoverflow.com/questions/27469219/toolbar-findviewbyid-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!