开发者

Android opening context menu after button click

开发者 https://www.devze.com 2023-02-25 00:27 出处:网络
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 oncli开发者_如何学Gock

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 oncli开发者_如何学Gock method?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号