2014-10-19 80 views
0

我得到這個listView這是從SQL數據庫通過自定義光標適配器填充。當我點擊一個項目時,對話框出現並要求確認以刪除該項目。如果我選擇YES,它將刪除列表中的項目和SQL條目,並且我重新加載列表並重新滾動到列表的頂部。 我想要做的是,當我刪除一個項目時,列表應該記住它的位置並顯示那個項目靠近那個已刪除的項目(我不希望它回到列表頂部)。我怎麼能做到這一點?listView滾動記憶

這裏是我的代碼(onItemClick和setListView方法):

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 

    final long arg3mod = arg3; 

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(HistoryActivityMod.this); 

    // Setting Dialog Title 
    alertDialog.setTitle("Confirm Delete..."); 

    // Setting Dialog Message 
    alertDialog.setMessage("Are you sure you want delete this?"); 

    alertDialog.setIcon(android.R.drawable.ic_menu_delete); 

    // Setting Positive "Yes" Button 
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog,int which) { 

      db.delete(DbHelper.TABLE_NAME, DbHelper.C_ID+"="+arg3mod, null); 
      setListView(); 

     Toast.makeText(getApplicationContext(), "Entry was deleted", Toast.LENGTH_SHORT).show(); 

     } 
    }); 


    // Setting Negative "NO" Button 
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 

     Toast.makeText(getApplicationContext(), "Nothing changed", Toast.LENGTH_SHORT).show(); 
     dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 

} 

public void setListView(){ 
    String[] columns= {DbHelper.C_ID, DbHelper.ROW1, DbHelper.ROW2, DbHelper.ROW3, DbHelper.ROW4, DbHelper.ROW5}; 

    Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC"); 

    CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(),cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); 

    lv.setAdapter(adapter); 

} 

回答

1

嘗試以下操作:

public void setListView(){ 
    String[] columns= {DbHelper.C_ID, DbHelper.ROW1, DbHelper.ROW2, DbHelper.ROW3, DbHelper.ROW4, DbHelper.ROW5}; 

    Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC"); 
    if(lv.getAdapter() == null) { 
     CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(),cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); 
     lv.setAdapter(adapter); 
    } else { 
     ((CustomCursorAdapter)lv.getAdapter()).changeCursor(cursor); 
    } 

} 
0

的問題是,你叫lv.setAdapter(adapter),這將導致您的列表重置頂部。您只能使用lv.setAdapter(adapter)一次,如果您的適配器是CursorAdapter,則可以使用其changeCursor(cursor)方法更新其下層數據。

因此,在您的setListView()方法中,您可以用adapter.changeCursor(cursor)代替lv.setAdapter(adapter)

參考文獻: https://developer.android.com/reference/android/widget/CursorAdapter.html#changeCursor(android.database.Cursor)

+0

我改變了它,但ListView控件中沒有加載。我應該在代碼中調用lv.setAdapter(adapter)? – Markonionini 2014-10-19 20:58:14

+0

創建適配器後。 – 2014-10-19 21:24:08

+0

也許我錯過了一些東西,但這不適合我。 – Markonionini 2014-10-19 22:34:33