我有一个对话框片段,其中有布局中的工具栏。我想让后退按钮(导航图标)在工具栏中工作,并在单击时退出片段。但是我无法在(对话框)片段中的工具栏导航图标上捕获点击事件。
这是我获取工具栏的方式:
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 许可协议
添加代码块
toolbar.setNavigationOnClickListener
之后setSupportActionBar(toolbar)