在DialogFragment中不会调用onContextItemSelected

时间:2013-04-10 14:42:56

标签: android android-dialogfragment android-contextmenu

我有一个显示项目列表的对话框,我需要能够编辑/删除此列表中的项目,因此我将上下文菜单放入其中,因此当用户长按项目时,他们可以选择他们想要的内容要做(编辑或删除项目)。

问题是当选择上下文菜单中的项目时,onContextItemSelected永远不会被调用。

我检查了创建对话框片段的活动是否可以获得回调,但这不是为什么它没有被调用?你不能在对话框中做一个上下文菜单吗?

public class TypesDialogList extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>,OnItemClickListener,OnCreateContextMenuListener{

ListView lv;
SimpleCursorAdapter mAdapter;
private int EDIT_TYPE = 1;
private int DELETE_TYPE = 2;
OnEditType mType;


public Dialog onCreateDialog(Bundle state){
    final View v = getActivity().getLayoutInflater().inflate(R.layout.layer_dialog_layout, null, false);
    lv = (ListView)v.findViewById(R.id.listView1);
    lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    lv.setOnItemClickListener(this);
    lv.setOnCreateContextMenuListener(this);
    return new AlertDialog.Builder(getActivity()).setView(v).setPositiveButton("Add Type", new OnClickListener(){

        public void onClick(DialogInterface dialog, int which) {

        }

    }).setTitle("Type's").create();
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
    super.onCreateContextMenu(menu, v, menuInfo);
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    long id = info.id;
    if(id > 3){
        menu.setHeaderTitle("Type Menu");
        menu.add(Menu.NONE, EDIT_TYPE, 1, "Edit");
        menu.add(Menu.NONE, DELETE_TYPE, 2, "Delete");
    }else{
        Toast.makeText(getActivity(),"Cannot edit type",Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    super.onContextItemSelected(item);
     AdapterView.AdapterContextMenuInfo oMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
     long id = oMenuInfo.id;
     if(item.getItemId() == EDIT_TYPE){

     }else if(item.getItemId() == DELETE_TYPE){

     }
     return true;
 }

}

1 个答案:

答案 0 :(得分:30)

对于仍在寻找解决方法的任何人,我刚刚通过创建匿名OnMenuItemClickListener来解决此问题,该匿名onContextItemSelected(MenuItem item)委托回@Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // Creation/inflate menu here OnMenuItemClickListener listener = new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { onContextItemSelected(item); return true; } }; for (int i = 0, n = menu.size(); i < n; i++) menu.getItem(i).setOnMenuItemClickListener(listener); } 并在菜单中的所有项目上进行设置。

{{1}}