Aayush Rana
Aayush Rana

Reputation: 1303

How to get selected item name form Context menu in android

I am using the android List View in my activity ...

Now i need get the name for the item selected from the list...

here's my code for menu create

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
       super.onCreateContextMenu(menu, v, menuInfo);         


     MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.activity_main, menu); //select layout which should pop up in context menu

     menu.add("Delete");
     menu.add("Rename");

}

what i need is the way to get the list view selected item's name in the following function which captures the click on Context menu.

@Override
public boolean onContextItemSelected(MenuItem item) 
{

     super.onContextItemSelected(item);


    if(item.getTitle()=="Delete"){
       //slected item's name in string varible here??
    }
    if(item.getTitle()=="Rename"){
            //slected item's name in string varible here??
    }
    return true;

}

Upvotes: 2

Views: 7571

Answers (2)

Paul
Paul

Reputation: 149

public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo itemInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int itemId = itemInfo.position; // Implements our logic

    if (item.getTitle()=="Add") {
        Toast.makeText(this, "Item id [" + itemId + "]", Toast.LENGTH_SHORT).show();


    }
    return true;

}

Upvotes: 1

BrickTop
BrickTop

Reputation: 230

to get the itemId use this:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

you can get the id of an item via

info.id

If you want to receive the name, you can also use to info.position to get the position of the item in the list. With the position you can get the item from the listView to get the name of the item

Upvotes: 6

Related Questions