2012-04-27 37 views
3

我試圖顯示綁定到我的ListView的每一行的數據庫值的小計。我不想將小計保留爲數據庫列,因此我試圖在顯示值時累計這些值。當然,這帶來了一個顯而易見的問題,就是如何處理滾動,這會顯示並重新顯示一個值,從而搞砸了運行的小計。在每個列表視圖行上顯示子彙總

詳細說明,每個listview行有兩個字段,一個值和一個小計。該值來自數據庫行,小計是直至幷包括該行的所有數據庫行的總和。如果我不需要,我不希望將小計納入數據庫行,因爲這會使插入和刪除行變得更加困難。

任何想法?

+0

小計是如何計算的? – candyleung 2012-04-27 02:43:29

+0

這是一個運行總數。把它看作一本支票簿,其中數據庫行包含支票金額,但不包括餘額。 – Digilee 2012-04-27 02:57:17

回答

2

創建自定義適配器,創建一個數組來保存分類彙總和使用,在您的getView維持即使在滾動時也是小計。

public class CustomCursorAdapter extends SimpleCursorAdapter { 

private Cursor c; 
private Context context; 
private Activity activity; 
private int[] subtotal; 
private int subtotalhold; 
private int layout; 

public CustomCursorAdapter(Context context, int layout, Cursor c, 
     String[] from, int[] to) { 
    super(context, layout, c, from, to); 

    this.c = c; 
    this.context = context; 
    this.activity = (Activity) context; 
    this.layout = layout; 

    subtotal = new int[c.getCount()]; 
    subtotalhold=0; 
    c.moveToFirst(); 
    int i = 0; 
    while (c.isAfterLast() == false) { 
     subtotalhold = subtotalhold + c.getInt(columnIndex); 
     subtotal[i] = subtotalhold; 
     i++; 
     c.moveToNext(); 
    } 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    if (convertView == null) 
     convertView = View.inflate(context, layout, null); 
    c.moveToPosition(position); 

    TextView subtotal = (TextView) convertView.findViewById(R.id.subtotal); 
      subtotal.setText(subtotal[position]); 

      // rest of your code to populate the list row 
    return (row); 
    } 
} 
+0

巴拉克,謝謝你的回答。我也考慮過這種方法,但數據庫中潛在行的數量可能需要大量的浮點數或雙精度數據,我不知道使用這種類型的內存有多好。我仍然可以這樣做,但我正在研究另一種方法。 – Digilee 2012-04-28 03:18:47

+0

我會給這個答案的凹凸,因爲我決定至少在臨時使用它,以便我可以繼續發展。任何其他建議仍然受歡迎。 – Digilee 2012-04-28 03:24:59

0

迭代通過被加載到ListView中,然後在同一時間計算它的價值...

+0

這就是我所做的,但是每當它滾動出視圖並回到視圖中時,相同的數據庫條目就會被加載,導致累加器不正確。 – Digilee 2012-04-27 03:26:32

+0

然後更改您的佈局,以便TextView不會離開屏幕。基本上將其固定在底部。 – JoxTraex 2012-04-27 03:27:45

+0

我不認爲你明白。我編輯了我的原始問題以使其更清楚(我希望)。 – Digilee 2012-04-27 03:42:49