lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position,
Solution:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
long itemID = info.position;
menu.setHeaderTitle("lior" + itemID);
}
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
gives you more details about the list item clicked.
Then you can use info.id, info.position
and so on to retrieve the details and use them actions (edit, delete...).
My Solution:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
mListView.showContextMenuForChild(view);
}
});
Regarding opening a context menu on a short click:
The other solutions posted here didn't work for me because I was using a ListFragment. However the following solution seems to work quite nicely for both a ListFragment and a ListActivity (or just any old listview in general):
public void onListItemClick(ListView l, View v, int position, long id){
l.showContextMenuForChild(v);
}
It's much more simple and elegant. In fact, this is actually how the ListView class itself initiates the context menu on a long click.
I was able to open a context menu on button click with the following code:
public void onButtonClickEvent(View sender)
{
registerForContextMenu(sender);
openContextMenu(sender);
unregisterForContextMenu(sender);
}
Just set the onClick property of the button to onButtonClickEvent. A long click won't trigger the context menu, since it is unregistrered right after it is shown.
In my case I had BaseAdapter and implemented click on button for each listView item (in getView method):
ImageButton menuBtn = (ImageButton) convertView.findViewById(R.id.itemListMenu);
menuBtn.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
parent.showContextMenuForChild(v);
}
});
I believe that if you add an OnLongClickListener to the view, you should be able to prevent it from showing the context menu on long click.
In onItemClick the view
parameter is the item view, so you should be able to get ImageViews or TextViews from that:
view.findById(R.id.my_image_view);