从列表视图中删除项目onlongclick

时间:2018-12-13 13:30:48

标签: android listview

我希望长按列表中的一个项目以提供一个选项删除,并在按下该项目时将其删除。

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

enter image description here

3 个答案:

答案 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)

您可以弹出一个对话框,要求用户确认。 但是,它不那么美观。我会推荐其中之一:

  1. 长按之后,在应用栏中显示一个删除选项(使用删除图标而不是文字)。
  2. 不支持长按,而是在每行的右/左使用带有可删除选项(再次带有图标)的可滑动行。 (我会推荐this库。

picture taken from the library page on github (gif来自here