Android opening context menu after button click

江枫思渺然 提交于 2019-11-30 06:11:26
dikirill

I was looking for the same, and found that instead of context menu, you should use Dialogs

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();
alert.show();

http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

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.

First thing, you should register the view by calling registerForContextMenu(View view). Second, override the onCreateContextMenu() to add the menus and lastly, override the onContextItemSelected() to put logic on each menu.

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:)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!