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?
Android context menu appears when user press long click on the element. It is also known as floating menu. It affects the selected content while doing action on it. It doesn't support item shortcuts and icons.
You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.). This is what the Android developer guide says: A ListAdapter that manages a ListView backed by an array of arbitrary objects.
One potential way to achieve is it set your ListView to height="wrap_content" If you do that then you can have override onTouchEvent() for your activity to get the events from when the user touches the empty space.
Context Menu is created by overriding the onCreateContextMenu() function. The menu resource is inflated by and calling the inflate() method of MenuInflater class.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With