2014-04-12 131 views
0

我有一個列表視圖,顯示不同配置文件的名稱,當用戶在項目上單擊時,該活動顯示一個alertDialog,如果用戶按下確認按鈕我想刪除該元素從我的列表視圖,從我的ArrayAdapter和從我的ArrayList。 我知道onItemLongClick方法中的arg2表示所選項目的索引,但我希望能夠在正面按鈕的onClick方法內訪問它。 有什麼建議嗎? 我的ArrayList被稱爲「ListaUtentiStringa」,ArrayAdapter是「profilesAdapter」,listView被稱爲listview。 對不起,我的英語不好。如何使用alertDialog從列表視圖中刪除項目

listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 

public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 


     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     builder.setCancelable(true); 
     builder.setTitle("Vuoi davvero cancellare il profilo?"); 
     builder.setPositiveButton("Si", new DialogInterface.OnClickListener() { 

          public void onClick(DialogInterface dialog, int which) { 
              // How to remove the selected item? 
          } 

         }); 

builder.setNegativeButton("Annulla", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 

     } 

     }); 

     AlertDialog alert = builder.create(); 
     alert.show(); 
     profilesAdapter.notifyDataSetChanged(); 


    return true; 
    } 
    }); 
+0

你可以通過你的項目的位置,你的警告對話框,如果刪除按鈕用戶按下,那麼你只需要刪除該位置的物品! – r4jiv007

+0

我怎麼能通過這個職位?我無法通過arg2 – Moltehh

回答

0

試試這個..

使用ListaUtentiStringaArrayListprofilesAdapteradapter全局變量

builder.setPositiveButton("Si", new DialogInterface.OnClickListener() { 

         public void onClick(DialogInterface dialog, int which) { 
             // How to remove the selected item? 

           ListaUtentiStringa.remove(arg2); 
           profilesAdapter.notifyDataSetChanged(); 
           dialog.dismiss(); 
         } 

        }); 

編輯

public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) { 
+0

但我無法引用arg2,因爲「無法引用在不同方法中定義的內部類中的非最終變量arg2」 – Moltehh

+1

@Moltehh使用'查看arg1,final int arg2,long arg3 ' – Hariharan

+0

如果我嘗試使用arg2(「不能在不同的方法中定義的內部類中引用非最終變量arg2」),我得到此錯誤 – Moltehh

1

這樣做:

listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 


@Override 
public boolean onItemLongClick(AdapterView<?> parent, View view, 
       final int position, long id) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     builder.setCancelable(true); 
     builder.setTitle("Vuoi davvero cancellare il profilo?"); 
     builder.setPositiveButton("Si", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
     // How to remove the selected item? 
      adapter.remove(adapter.getItem(position)); 
     } 

    }); 
+0

我無法對位置變量進行引用,我寫了一條評論中的錯誤 – Moltehh

+0

@Moltehh編輯了我的代碼。嘗試這個。 –

+0

它的工作表示感謝! – Moltehh

相關問題