众所周知,用SimpCursorAdapter可以很方便的把数据库中的数据绑定到前台显示,但是有时候数据库中取出的数据,并不是我们要直接显示的数据,而是想稍作修改再表示出来,比如时间在数据库中一般是以毫秒(milisecond)显示,但此时你需要的数据可能是采用时分秒的形式表示的,那么此时怎么办呢。
也许你会采用自定义一个继承自cursorAdapter 的适配器,然后重写。不错,这是个不错的方法,很原始,也很实用。但这里还有另一种比较简单的方法。
private SimpleCursorAdapter.ViewBinder viewBinder=new SimpleCursorAdapter.ViewBinder() {
//创建一个viewBinder,创建了viewBinder就必须要重载setViewValue这个方法
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
// TODO Auto-generated method stub
if(cursor.getColumnIndex("duration")==columnIndex){ //duration为数据库中对应的属性列
TextView tv=(TextView)view;
tv.setText(""+(cursor.getInt(columnIndex)/1000); //将数据库中的数据除以1000以后在显示
return true;
}
return false;
}
};
simpleCursorAdapter.setViewBinder(viewBinder);
其原理就是:
对应于
SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)
view就是你SimpleCursorAdapter里面传入的 String[] from 资源,cursor就是你的数据集c,columnIndex就是当前正在进行匹配的列。如果你cursor.getColumnIndex("duration")这列需要进行数据转换等操作,则在setViewValue内进行转换,则返回true
其他列匹配时则没进行操作,返回false
---------------------
作者:朝朝之花夕夕来拾
来源:优快云
原文:https://blog.youkuaiyun.com/dnfchan/article/details/6826860
版权声明:本文为博主原创文章,转载请附上博文链接!