2012-07-30 80 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

相关问题