已经能够使用 onItemLongClick 方法删除 ListView 项,但我宁愿使用 float 上下文菜单来执行此操作。
下面是我目前拥有的用于 float 上下文菜单的代码。我按照帮助我设置它的文档进行操作,然后尝试搜索与我正在做的事情类似的示例,但找不到任何合适的示例。
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.payments_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
return true;
case R.id.delete:
return true;
default:
return super.onContextItemSelected(item);
}
}
这是在我决定切换到 float 上下文菜单之前必须删除 ListView 中的项目的代码
public boolean onItemLongClick (AdapterView<?> parent, View view, int position, long id)
{
String temp = paymentTitle.get(position).toString();
paymentTitle.remove(position);
paymentDate.remove(position);
reminderDate.remove(position);
reminderTime.remove(position);
paymentVal.remove(position);
mDatabase = new MOSDatabase(this);
SQLiteDatabase readableDB = mDatabase.getWritableDatabase();
readableDB.delete("PaymentTable", "PTITLE=?",
new String[]{temp});
aa.notifyDataSetChanged();
return false;
}
如果有人可以建议我如何使这个 float 上下文菜单正常工作,我将不胜感激。我还没有完成编辑方法,这是我完成后要做的。
最佳答案
如果我没理解错的话,可以通过下面的代码获取点击位置ListView中item的索引:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
使用 position
,你可以重用 onItemLongClick
的代码:
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
switch (item.getItemId()) {
case R.id.edit:
return true;
case R.id.delete: {
String temp = paymentTitle.get(position).toString();
paymentTitle.remove(position);
paymentDate.remove(position);
reminderDate.remove(position);
reminderTime.remove(position);
paymentVal.remove(position);
mDatabase = new MOSDatabase(this);
SQLiteDatabase readableDB = mDatabase.getWritableDatabase();
readableDB.delete("PaymentTable", "PTITLE=?",
new String[]{temp});
aa.notifyDataSetChanged();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
您可能想查看 this 的答案问题。
关于android - 使用 float 上下文菜单从 ListView 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18363650/