How to catch navigation icon click on toolbar from

2020-05-20 05:15发布

问题:

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

回答1:

add code block toolbar.setNavigationOnClickListener after setSupportActionBar(toolbar)



回答2:

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


回答3:

 toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:

                  // do what ever you want here
            }
            return true;
        }
    });