问题
I've a ListView with a 'classic' context menu with delete and similar options. Since I'm deleting from a SharedPreferences object, I need to retrieve the key, which is the text set into ListView's items.
I've tried the following code:
@Override
public boolean onContextItemSelected(MenuItem item){
AdapterContextMenuInfo saved = (AdapterContextMenuInfo) item.getMenuInfo();
TextView view = (TextView)findViewById((int) saved.id);
Log.d("DEBUG:", "before key");
String key = view.getText().toString();
Log.d("DEBUG:", "after...");
switch (item.getItemId()){
case R.id.conmenu_delete:
return true;
case R.id.conmenu_copy:
return true;
case R.id.conmenu_send:
return true;
default:
return super.onContextItemSelected(item);
}
}
But, unfortunately, it crashes while trying to retrieve the text from the View, as I know from logs.
回答1:
You have already correctly casted the AdapterContextMenuInfo
.
From there, you can get the targetView which you can cast again into the widget. I guess it's a TextView
in your case. On that TextView
you can call the simple getText()
method.
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String key = ((TextView) info.targetView).getText().toString();
switch (item.getItemId()){
case R.id.conmenu_delete:
return true;
case R.id.conmenu_copy:
return true;
case R.id.conmenu_send:
return true;
default:
return super.onContextItemSelected(item);
}
}
If your list is populated with custom objects, you obviously have to cast it to the respective type, for example:
Person person = (Person) getListAdapter().getItem(info.position);
String key = person.getName();
回答2:
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Object obj = getListView().getItemAtPosition(info.position);
String title = obj.toString();
}
来源:https://stackoverflow.com/questions/14328596/retrieving-text-from-a-listview-item-with-oncontextitemselected