我有一个带有删除和类似选项的“经典”上下文菜单的 ListView。因为我要从 SharedPreferences 对象中删除,所以我需要检索键,这是设置到 ListView 的项目中的文本。
我试过下面的代码:
@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);
}
}
但是,不幸的是,正如我从日志中了解到的那样,它在尝试从 View 中检索文本时崩溃了。
最佳答案
您已经正确地转换了 AdapterContextMenuInfo
。
从那里,您可以获得可以再次转换到小部件中的 targetView。我猜你的情况是 TextView
。在那个 TextView
上,您可以调用简单的 getText()
方法。
@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);
}
}
如果您的列表中填充了自定义对象,您显然必须将其转换为相应的类型,例如:
Person person = (Person) getListAdapter().getItem(info.position);
String key = person.getName();
关于android - 使用 OnContextItemSelected 从 ListView 项中检索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14328596/