gpt4 book ai didi

android - 从 ListView 中删除项目 onlongclick

转载 作者:行者123 更新时间:2023-11-29 23:24:30 28 4
gpt4 key购买 nike

我想在长按列表中的某个项目时给出一个选项删除,如果按下则删除该项目。

//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,它工作正常,但没有像下面的照片那样为用户提供按删除的选项

 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;
// }
// });
}

enter image description here

最佳答案

将此添加到您的 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

关于android - 从 ListView 中删除项目 onlongclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53762999/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com