Search code examples
androidandroid-toolbar

How to access a button in toolbar?


I have a custome toolbar in application like below there is a button call logout

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

I have include this toolbar in my main activity like below

<include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>

in my main activity I have get that toolbar like below

mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);

How can I access the button in that toolbar I want to create a onclickevent how can i do that?


Solution

  • You can use findViewById on each View. So you can use

    Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);
    

    But as you included the toolbar layout in your root layout, it should be even enough to use

    Button button = (Button) findViewById(R.id.toolbar_logo_image);
    

    Both should work.

    EDIT: Your app_bar_toolbar.xml has a FrameLayout as root element, but in code you're trying to cast it to Toolbar. That can't work and will crash with a ClassCastException. So change your FrameLayout to a Toolbar or cast the FrameLayout correctly. Depends on your needs.