如何从片段中捕获导航图标点击工具栏?

新手上路,请多包涵

我有一个对话框片段,其中有布局中的工具栏。我想让后退按钮(导航图标)在工具栏中工作,并在单击时退出片段。但是我无法在(对话框)片段中的工具栏导航图标上捕获点击事件。

这是我获取工具栏的方式:

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

这是我的对话框片段布局文件:

 <?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>

**这是到目前为止已经尝试但失败的方法**

选项项点击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() :

 toolbar.setNavigationOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Back clicked!",     Toast.LENGTH_SHORT).show();
            }
        });

原文由 priyankvex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 304
2 个回答

添加代码块 toolbar.setNavigationOnClickListener 之后 setSupportActionBar(toolbar)

原文由 Dandong Wang 发布,翻译遵循 CC BY-SA 3.0 许可协议

这对我有用。

 toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"your icon was clicked",Toast.LENGTH_SHORT).show();
    }
});

原文由 Badr El Amrani 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题