Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch navigation icon click on toolbar from fragment?

I have a dialog fragment in which I have toolbar in layout. I want to make back button(Navigation Icon) working in toolbar and exit the fragment when clicked. But I am unable to catch the click event on the toolbar's navigation icon in the (dialog)fragment.

Here is how I am getting toolbar :

toolbar = (Toolbar) rootView.findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); toolbar.setTitle(itemType); ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); 

Here is my layout file for the dialog fragment :

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout          xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="@color/panel_cyan"     android:id="@+id/rootLayout"     >  <android.support.v7.widget.Toolbar     android:id="@+id/toolbar"     android:layout_width="match_parent"     android:layout_height="?attr/actionBarSize"     android:layout_alignParentLeft="true"     android:layout_alignParentStart="true"     android:layout_alignParentTop="true"     android:background="@color/color_primary"     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"     app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />  <ListView     android:layout_width="match_parent"     android:layout_height="match_parent"     android:id="@+id/listViewItems"     />  </RelativeLayout> 

**Here is what is have tried so far but failed **

Options item click in id R.id.home

 @Override     public boolean onOptionsItemSelected(MenuItem item) {         int id = item.getItemId();         switch (id){             case android.R.id.home:                 finish();                 break;         }         return super.onOptionsItemSelected(item);     } 

setNavigationOnClick() on the toolbar :

toolbar.setNavigationOnClickListener(new View.OnClickListener(){             @Override             public void onClick(View view) {                 Toast.makeText(getActivity(), "Back clicked!",     Toast.LENGTH_SHORT).show();             }         }); 
like image 633
priyankvex Avatar asked Jul 09 '15 08:07

priyankvex


2 Answers

add code block toolbar.setNavigationOnClickListener after setSupportActionBar(toolbar)

like image 50
Dandong Wang Avatar answered Sep 22 '22 18:09

Dandong Wang


This works for me.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {     @Override     public void onClick(View v) {         Toast.makeText(getApplicationContext(),"your icon was clicked",Toast.LENGTH_SHORT).show();     } }); 
like image 22
Badr El Amrani Avatar answered Sep 24 '22 18:09

Badr El Amrani