删除列表中长按监听器上的项目

时间:2019-04-29 09:15:43

标签: android android-listview onlongclicklistener

我想从列表中删除项目onsetOnItemLongClickListener.i已从数据库类中调用agetAssetData方法并将其添加到列表中,并在create方法中调用了此delete方法,但是在单击列表中的项目时,它未显示任何删除选项,如我的代码。

    dataModelAssetDataArrayList =
            new ArrayList <>(databaseAssetData.getAssetData());

    dataAdapterAssetData = new DataAdapterAssetData(this, dataModelAssetDataArrayList);

public void DeleteItem(){

    listViewAssetData.setAdapter(dataAdapterAssetData);

    listViewAssetData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        // setting onItemLongClickListener and passing the position to the function
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int position, long arg3) {
            removeItemFromList(position);

            return true;
        }


        // method to remove list item
        protected void removeItemFromList(int position) {
            final int deletePosition = position;

            AlertDialog.Builder alert = new AlertDialog.Builder(
                    EditViewAssetDataActivity.this);

            alert.setTitle("Delete");
            alert.setMessage("Do you want delete this item?");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TOD O Auto-generated method stub

                    // main code on after clicking yes
                    list.remove(deletePosition);
                    dataAdapterAssetData.notifyDataSetChanged();
                    dataAdapterAssetData.notifyDataSetInvalidated();

                }
            });
            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            alert.show();
        }

    });
}

1 个答案:

答案 0 :(得分:0)

  list.remove(deletePosition);    
  dataModelAssetDataArrayList.remove(deletePosition); //Must remove before notifyDataSetChanged
  dataAdapterAssetData.notifyDataSetChanged();