我正在使用 SimpleCursorAdapter 来填充 Android ListView,并且想知道我应该如何获取我从数据库中获得的所有时间戳,每个时间戳都在“DATE_DATE”中为人类可读的日期,也许使用 SimpleDateFormat?
Cursor programDateCursor = mDbAdapter.loadProgramDates();
startManagingCursor(programDateCursor);
String[] from = new String[]{ "DATE_DATE" };
int[] to = new int[]{ R.id.text1 };
SimpleCursorAdapter programDates =
new SimpleCursorAdapter(this, R.layout.program_date,
programDateCursor, from, to);
setListAdapter(programDates);
我没有用 Java 做过很多工作,所以有没有更好的方法/任何方法来做到这一点?除了预先将预格式化的日期存储在数据库中之外,那是什么?
最佳答案
您将必须创建一个自定义 CursorAdapter 才能格式化您的时间戳。
public class MyAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public MyAdapter(Context context, Cursor cursor) {
super(context, cursor, false);
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.program_date, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
long time = cursor.getLong(cursor.getColumnIndex("DATE_DATE")) * 1000L;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
String format = "M/dd h:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
String dateString = sdf.format(cal.getTime());
((TextView) view.findViewById(R.id.text1)).setText(dateString);
}
}
根据您的喜好更改字符串格式
的列表是here .
然后您可以将此适配器用于
Cursor programDateCursor = mDbAdapter.loadProgramDates();
startManagingCursor(programDateCursor);
setListAdapter(new MyAdapter(this, programDateCursor));
关于java - Android - 使用游标适配器在 ListView 中格式化时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6417550/