DenShlk
DenShlk

Reputation: 47

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.

Upvotes: 3

Views: 3336

Answers (3)

Htue Ko
Htue Ko

Reputation: 177

You can used setNavigationOnClickListener {} for this.

// I used private function here, you don't need to.
private fun onBackArrowPressed() {
    // when user clicked the navigation icon (here is back arrow)
    binding.toolbar.setNavigationOnClickListener {
        // find the nav controller and pop backstack
        findNavController().popBackStack()
    }
}

Material Components Android Top AppBar

Upvotes: 0

Ganesh MB
Ganesh MB

Reputation: 1189

Try this,

Toolbar toolbar;

toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

Upvotes: 1

user12755203
user12755203

Reputation:

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
        }
    });

Upvotes: 1

Related Questions