hleroy
hleroy

Reputation: 463

How to get the Button view which triggered a Context Menu?

I'm creating dynamically Button views with a context menu. When a context menu item is selected, I would like to retrive the Button view which triggered the context menu.

This is how I create the button :

// Create a new button
Button buttonView = new Button(this);
// Set button text
buttonView.setText("MyButton");
// Set on click listener
buttonView.setOnClickListener( new ButtonClickHandler() );
// Register for context menu
registerForContextMenu(buttonView);

This is how I create the context menu :

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}

And this is how I handle selected items :

public boolean onContextItemSelected(MenuItem item) {

    // Get extra menu information about the item selected   
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    // 
    switch (item.getItemId()) {
    case R.id.delete:

        // Retrieve selected button text
        String btnText = ((Button) info.targetView).getText().toString();
        // etc...
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

The issue is that "(AdapterContextMenuInfo) item.getMenuInfo()" returns null, i.e. there is no extra information about the item. I was expecting to get the Button view in info.targetView. Apparently this works only for ListView, because AdapterView takes care of populating this extra info.

I guess I should do something in "onCreateContextMenu" to attach this information. A sample code to attach this information would be very much welcomed.

Thanks

Upvotes: 3

Views: 4789

Answers (1)

Phil
Phil

Reputation: 36289

The Button that was used to create the context menu is the View parameter passed into onCreateContextMenu.

Upvotes: 2

Related Questions