我正在使用ViewPager
.我有两个选项卡,因此有两个片段,每个片段都有自己的上下文菜单选项。我的问题是,当我单击片段 B 中的上下文菜单选项时,会调用片段 A 中onContextItemSelected()
的方法。我该如何解决这个问题?
我按照官方Android文档中所示的操作进行操作: https://developer.android.com/guide/topics/ui/menus.html#context-menu
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
PositionClicked = info.position;
switch (item.getItemId()) {
case R.id.menu_edit:
return true;
case R.id.menu_archive:
return true;
case R.id.menu_report:
return true;
case R.id.menu_delete:
Log.i(TAG, "Delete Menu Buttom");
new AlertDialog.Builder(getActivity()).setTitle("Tem certeza?")
.setMessage("Você está prestes a deletar sua Postagem!")
.setPositiveButton("Deletar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//ShowSwipeRefreshin();
delete_item(MongodbObjtoDelete);
DialogResp = true;
feedItems.remove(PositionClicked);
listAdapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancelar", null).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
你可以像这样修复它:
FragmentManager manager = getFragmentManager();
if (manager.findFragmentByTag("frag1").isVisible()){
// do fragment 1
}else{
}
工作上下文菜单的示例
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("");
menu.setHeaderIcon("");
String[] menuItems = getResources().getStringArray(R.array.ContextMenu);
for (int I = 0; I < menuItems.length; I++) {
menu.add(Menu.NONE, I, I, menuItems[I]);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
if(menuItemIndex == 0){
//do something
}
return true;
}
还要检查哪些视图注册了上下文菜单。
registerForContextMenu(view);