2012-07-30 79 views
2

我用下面的SimpleCursorAdapter:是否可以使用SimpleCursorAdapter格式化一個double?

String campos[] = { "nome_prod", "codbar_prod", 
     "marca_prod", "formato_prod", "preco"}; 
int textviews[] = { R.id.textProdName, R.id.textProdCodBar, R.id.textProdMarca, 
     R.id.textProdFormato, R.id.textProdPreco }; 
CursorAdapter dataSource = new SimpleCursorAdapter(this, R.layout.listview, 
     c_list, campos, textviews, 0); 

這工作得很好。但是「campos []」的「preco」來自雙重價值。我能否以某種方式對其進行格式設置,以便我的光標(它提供一個列表視圖)在點之後顯示這個雙精度數字(例如貨幣值)?

我可以用一些簡單的方法做到嗎,比如在某處使用「%.2f」,或者我必須繼承CursorAdapter?

在此先感謝。

回答

4

您不需要繼承CursorAdapter。只需創建一個ViewBinder並將其附加到適配器,它將轉換光標特定列的值。像這樣:

dataSource.setViewBinder(new ViewBinder() { 
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 

     if (columnIndex == 5) { 
       Double preco = cursor.getDouble(columnIndex); 
       TextView textView = (TextView) view; 
       textView.setText(String.format("%.2f", preco)); 
       return true; 
     } 
     return false; 
    } 
}); 
+0

非常好的解決方案。 – Krylez 2012-07-30 19:19:15

+0

似乎正是我想要的,但我得到了這個錯誤:'java.util.IllegalFormatConversionException:%f不能格式化java.lang.String參數 ' – user1531978 2012-07-30 19:31:53

+1

使用cursor.getDouble(columnIndex)來獲取double值和反饋給您的字符串格式化程序。如果您要格式化金額,建議使用CurrencyFormatter而不是String.format。 – CSmith 2012-07-30 19:36:33

相關問題