我希望长按列表中的一个项目以提供一个选项删除,并在按下该项目时将其删除。
//onCreate()
alreadyAddedFood = (ListView) findViewById(R.id.alreadyAddedList);
registerForContextMenu(alreadyAddedFood);
//END of onCreate()
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_general, menu);
menu.setHeaderTitle("Select The Action");
}
@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getItemId()==R.id.delete){
//How to delete?
Toast.makeText(getApplicationContext(),"delete"+item,Toast.LENGTH_LONG).show();
}else{
return false;
}
return true;
}
更新
我也有一个此类,我实现了onlongClickListener,它可以正常工作,但没有向用户提供按下Delete的选项,如下面的照片
public void alreadyAdded(String searchedMessage) {
itemsAdded.add(searchedMessage);
final ArrayAdapter<String>addedAdapter= new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemsAdded);
alreadyAddedFood.setAdapter(addedAdapter);
alreadyAddedFood.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// @Override
// public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// itemsAdded.remove(position);
// addedAdapter.notifyDataSetChanged();
// Toast.makeText(AddFood.this, "Item Deleted", Toast.LENGTH_LONG).show();
// return true;
// }
// });
}
答案 0 :(得分:1)
将此添加到您的onContextItemSelected
中:
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // init the info to get the position from
items.remove(info.position); // remove the item from the list
adapter.notifyDataSetChanged(); //updating the adapter
答案 1 :(得分:0)
您可以执行以下操作:
private ListView ls;
ls.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int arg2, long arg3) {
ls.remove(arg2);//where arg2 is position of item you click
myAdapter.notifyDataSetChanged();
return false;
}
});
答案 2 :(得分:0)