2014-02-11 112 views
0

我想使用OnItemLongClickListener從ListView中刪除項目。
這是我的代碼,當我OnLongClick項目時出現AlertDialog。
我還需要現在,當我刪除項目使用OnItemLongClickListener刪除項目

public class DeleteItem extends Activity { 

ListView list; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

     list = (ListView) findViewById(R.id.listView); 
     list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

      @Override 
      public boolean onItemLongClick(AdapterView<?> arg0, View arg1, 
        int arg2, long arg3) { 
       AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this); 
       alert.setMessage("Are you sure you want to delete this?"); 
       alert.setCancelable(false); 
       alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         //Here I need the delete code 
        } 
       }); 
       alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         dialog.cancel(); 

        } 
       }); 


       return false; 

      } 
     }); 

     } 
    } 
+1

你有什麼樣的適配器 – Blackbelt

+2

沿着1)從你正在使用的數組中刪除項目來填充列表2)調用notifyDataSetChanged() – csmckelvey

+0

我有一個ArrayAdapter – user3267319

回答

0

ArrayAdapter有方法remove(int index)什麼代碼使用方法:

list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

     @Override 
     public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, 
       final int position, long arg3) { 
      AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this); 
      alert.setMessage("Are you sure you want to delete this?"); 
      alert.setCancelable(false); 
      alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        ArrayAdapter yourArrayAdapter = (ArrayAdapter) arg0.getAdapter(); 
        yourArrayAdapter.remove(position); 
        yourArrayAdapter.notifyDataSetChanged(); 
       } 
      }); 
      alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 

       } 
      }); 


      return false; 

     } 
    }); 

調整與通用型適配器的演員。它只適用於將適當的元素集合提供給適配器的情況。如果你提供了一個數組,它會拋出一個異常