mungaih pk mungaih pk - 4 months ago 35
Android Question

Using contextmenu with listview in android

I am developing an android application.I will have a listview and i have set a context menu to appear when a listview item is long-pressed.How do i get the item from the listview item selected(say text from a listview textview) after an action from the contextmenu is chosen so i can process it?
Here is some code:

protected void onCreate(Bundle savedInstanceState) {
-------
lv1 = (ListView) findViewById(R.id.listings);

registerForContextMenu(lv1);
lv1.setOnItemClickListener(this);

}


And the onCreateContextMenu:

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

@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.watch:
String name = "";
return true;
case R.id.buy:
return true;
default:
return super.onContextItemSelected(item);
}
}


I want to get text from a textview in a list item.How do i achieve that?

Answer

you should register the LISTVIEW for the context menu.

Here's the source.

for onCreate():

 registerForContextMenu(lv);

And to access the selected item during long click:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
   if (v.getId() == R.id.lv) {
       ListView lv = (ListView) v;
       AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
       YourObject obj = (YourObject) lv.getItemAtPosition(acmi.position);

       menu.add("One");
       menu.add("Two");
       menu.add("Three");
       menu.add(obj.name);
   }
}