使用SimpleCursorAdapter从Cursor更改值

Gio*_*gio 27 sqlite android filtering cursor

我有数据库表,列{名称,时间(UTC格式),纬度,经度}

我使用带有SimpleCursorAdapter的ListActivity显示表.

我希望列Time以人类可读格式显示时间(13-07-2010 10:40)而不是UTC格式(18190109089).

如何指定列Time中的值需要一些过滤/适应?

可能的解决方案(有问题):

SimpleCursorAdapter提供的方法:

setCursorToStringConverter(SimpleCursorAdapter.CursorToStringConverter cursorToStringConverter);
Run Code Online (Sandbox Code Playgroud)

指定一个能够将Cursor转换为CharSequence的类(convertToString(Cursor cursor).无论如何我不知道返回CharSequence参数的格式应该是多少!

小智 74


格式化游标值的最简单方法是使用SimpleCursorAdapter.setViewBinder(..):

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list, cursor,
            new String[] { Definition.Item.TITLE, Definition.Item.CREATE_DATE }, new int[] { R.id.title, R.id.createDate});

adapter.setViewBinder(new ViewBinder() {

    public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {

        if (aColumnIndex == 2) {
                String createDate = aCursor.getString(aColumnIndex);
                TextView textView = (TextView) aView;
                textView.setText("Create date: " + MyFormatterHelper.formatDate(getApplicationContext(), createDate));
                return true;
         }

         return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 请记住,`aColumnIndex`是"可以在光标中找到数据的列".我用`Cursor.getColumnIndex`来比较. (6认同)

小智 13

经过长时间的斗争,我也遇到了同样的问题,最后我找到了答案:)(见下文)

use setViewText (TextView v, String text)
Run Code Online (Sandbox Code Playgroud)

例如

SimpleCursorAdapter shows = new SimpleCursorAdapter(this, R.layout.somelayout, accountCursor, from, to)
{
 @Override
 public void setViewText(TextView v, String text) {
 super.setViewText(v, convText(v, text));
}    
};

private String convText(TextView v, String text)
{

 switch (v.getId())
 {
 case R.id.date:
             String formatedText = text;
             //do format
            return formatedText;
        }
return text;
}
Run Code Online (Sandbox Code Playgroud)