Search code examples
androidcallonclicklistenertoolbarandroid-toolbar

Call navigation icon click in toolbar (android)


I have code below:

setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(onClickListener);

and XML:

<com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:paddingStart="0dp"
            android:paddingEnd="12dp"
            app:contentInsetStart="0dp"
            app:navigationIcon="@drawable/ic_menu_black_24dp"
            app:title="@string/app_name" />
    </com.google.android.material.appbar.AppBarLayout>

I want to call click on navigation icon of toolbar, but i cant find method to do it. I can't call onClickListener(null) because I change icon inside onClick.


Solution

  • Please try this by replacing 'number' with the index of the icon. (It could be 1-2-3-4 etc.)

        toolbar.getChildAt(number).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //do whatever you want here
            }
        });