用android开发一个记事本应用,就需要在每一个条目下,添加一个时间戳,显示修改时间。记事本的内容存在SQLITE中,通过游标cursor读取数据,并通过SimpleCursorAdapter将装配到对应的layout布局中。我们常常会遇到这样一个问题,获取系统时间用的是System.currentTimeMillis()【返回值为long,用于获取当前的时间,单位是毫秒ms】。而我们要显示的是“年月日,时分秒”的格式。 下面以修改谷歌notepad的demo做一个讲解。notepad源码可以从https://github.com/llfjfz/NotePad下载
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE} ;//游标中数据的列名
int[] viewIDs = { R.id.text1,R.id.timestamp1};//对应标签的ID号
SimpleCursorAdapter adapter
= new SimpleCursorAdapter(
this,
R.layout.noteslist_item,//对应的布局
cursor, //游标
dataColumns,//游标中的列名
viewIDs, //游标中列名对应的,布局中的标签的ID号
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
);
setListAdapter(adapter);
布局文件,一个线性布局中包含两个TextView ,id分别为text1和timestamp1。
<?xml version="1.0" encoding="utf-8"?>
<!--notepad便签条目显示界面的,listadapter 每个条目对应的layout-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:singleLine="true"
android:textSize="30dp"
android:text="这里放title,也就是
NotePad.Notes.COLUMN_NAME_TITLE对应的数据"
/>
<TextView
android:id="@+id/timestamp1"
android:layout_width="match_parent"
android:layout_height="25dp"
android:textAlignment="center"
android:textSize="18dp"
android:gravity="center_vertical"
android:text="这里放最近修改时间,也就是
NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE对应的数据"
/>
</LinearLayout>
修改之后就实现了时间戳的基本效果 ,如图
但是我们发现,通过System.currentTimeMillis()得到的时间单位是ms,简直没法看,这时候就需要进行格式转化了。百度可知,使用 SimpleDateFormat 可以很方便的进行格式转化,如
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss",Locale.CHINA);
Date date=new Date(System.currentTimeMillis());
String time=format.format(date);
Log.d("TIME", time);//输出结果
各种时间的样式,可以百度,我就不赘述了,主要讲一下如何将SimpleCursorAdapter的数据显示成转化后的数据格式。普遍使用的有两种方法:
1.重写SimpleCursorAdapter
2.使用SimpleCursorAdapter.ViewBinder
我主要介绍一下第二种方法,首先先看代码:
SimpleCursorAdapter.ViewBinder viewBinder=new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int i)
{
if(cursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE)==i){
TextView textView1=(TextView)view;
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss",Locale.CHINA);
Date date=new Date(cursor.getLong(i));
String time=format.format(date);
Log.d("TIME", "onCreate1:"+time);
textView1.setText(time);
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
简单来讲,就是重写ViewBinder的setViewValue,在其中用if做一个判断,如果cursor选取的内容为你想要修改的内容,就进行自定义的操作,如修改时间格式,之后需要返回true,表示做了修改。如果是其他的数据不做修改,返回false,由SimpleCursorAdapter做默认的装配数据。