Sai
Sai

Reputation: 15718

How to open the ContextMenu from MenuItem Android

So, I know we need to pass a view to openContextMenu(view); but where can i get the view for Menuitem, please have a look at my code. Thanks in advance.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.actionmenu:
        openContextMenu(item); //I dont know what to pass here
        break;
    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Select The Action");
        menu.add(0, 0, 11, "Edit");
        menu.add(0, 1, 12, "Delete");

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        System.out.println(item.getItemId());
        return super.onContextItemSelected(item);
    }

Upvotes: 0

Views: 822

Answers (1)

Weiyi
Weiyi

Reputation: 1933

1. Register a view for a floating context menu

By default, a long-press on a view does not trigger the creation of a context menu. You must register a view for a floating context menu by calling the following method, a listview for example:

ListView listView = (ListView) v.findViewById(android.R.id.list);
registerForContextMenu(listView);    

2. Create resource xml file

You'd better to create a xml resource file that contains the context menu item:

your_context.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/context_menu_eidt"
        android:title="Edit" />

    <item android:id="@+id/context_menu_delete"
        android:title="Delete" />
</menu>

3. Inflate the resouce to build context menu

Then inflate the resource file in onCreateContextMenu method, the parameter @v is the view that the context menu is being built for:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    if (v.getId() == android.R.id.list) {
        Log.d(TAG, "get the view here");
    }

    getActivity().getMenuInflater().inflate(R.menu.your_context, menu);
}

4. Do something when menu item selected

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int position = info.position; 

    switch (item.getItemId()) {
    case R.id.context_menu_eidt:
        // TODO
        return true;
    case R.id.context_menu_delete:
        // TODO
        return true;
    }

    return super.onContextItemSelected(item);
}

That's all.

Upvotes: 1

Related Questions