masmic
masmic

Reputation: 3564

Get ContextMenu item ID

I have a simple layout where there are few textviews. Here what I do is define a name, and save it into a database using a contentProvider. Then, this name is read from the database and shown on the textView.

This is how I first get the item saved on the database:

Cursor c = getContentResolver().query(TravelersProvider.CONTENT_URI, PROJECTION, null, null, null);

The projection is:

String[] PROJECTION = {Travelers._ID, Travelers.NAME};

Now What I need to do is:

This is the way I register the contextMenu to the TextView:

txtView1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        registerForContextMenu(v);
    }
});

Then I create it:

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

And finally I define what to do when touching:

@Override
public boolean onContextItemSelected(MenuItem item) {
    //TODO:
}

Here is where I need some help. Basically, what I need to do is:

Upvotes: 0

Views: 856

Answers (1)

ashishduh
ashishduh

Reputation: 6699

In the onCreateContextMenu hook, there is a View parameter. Call getId() on this parameter to determine which TextView invoked the context menu. Then you can store this into a class variable to be used in onContextItemSelected.

private int contextViewId;

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.context_menu, menu);
    contextViewId = v.getId();
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    // use contextViewId
}

Upvotes: 1

Related Questions