Alex Rivera | Logout

Android opening context menu after button click

Asked 2011-04-13T06:26:22.487
21

I want to open context menu when I click a button, but also I have to know which list item is focused when I click the button. Do you know how to do that? What code should be in onclick method?

Edit
Report

2 Answers

26

If you really want to do it for whatever reason... (in my case, out of laziness)

During onCreate of your activity or somewhere before your user can touch the button, do registerForContextMenuon that button. Then in the actual button onClick handler, call openContextMenu(View).

For example, I have a button declared in xml like

<Button
    android:id="@+id/btn_help"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onHelp"
    android:text="@string/help_btn_text" />

in my onCreate

registerForContextMenu(findViewById(R.id.btn_help));

and in onHelp function

public void onHelp(View v) {
    openContextMenu(v);
}

this works because the View v is the same as the view registered for context menu.

answered 2012-05-04T22:39:44.720
1

First of all, you should know why you should use ContextMenu. The functionality of ContextMenu of a View is similar to the right-click menu on a PC, which means the "available operations" on some item.

According to your description, I think what you actually need is a customized Dialog with a list, which is displayed when clicking the Button and is also able to get the focused item of your ListView. Then you can save the registration of ContextMenu for some View that really needs the menu:)

answered 2011-04-13T07:15:06.683

Your Answer