摘要: Android Email app 来举个例子,这种app需要的基本功能中有 1. 从服务器接收的Email数据保存在本地数据库里面(SQLite) 2. Email数据中除了内容以外还会有一个boolean 变量(也可以用int 0/1 代替)来标记“已读”“未读”。
简单来说从SQLite里面读取已读变量,让系统在app中的List上画一个Checkbox。(根据SQLite里面的数据)
1. 首先定义一个 SimpleCursorAdapter.ViewBinder
SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view instanceof CheckBox) {
CheckBox checkbox = (CheckBox)view;
int value = cursor.getInt(columnIndex);
if(value==1) {
checkbox.setChecked(true);
return true;
}
else if(value==0) {
checkbox.setChecked(false);
return true;
}
else
return false;
}
return false;
}
};
注:Cursor的可以有好几个行,这里的columnIndex表示一个行的索引。
2. 下面定义一个SimpleCursorAdapter本身 然后利用 SimpleCursorAdapter.setViewBinder()来套用之前定义的ViewBinder。
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item,
notificationCursor, new String[] { "subject", "content", "date", "unread"},
new int[] {R.id.subject, R.id.content, R.id.date, R.id.unread});
simpleCursorAdapter.setViewBinder(viewBinder);
注:这里的R.id.unread是指布局xml文件的里的CheckBox部件。 R.id.subject, R.id.content, R.id.date是其他Email数据。
ListAdapter adapter = simpleCursorAdapter;
setListAdapter(adapter); // Activity 是 ListActivity
3. 这样就完事了,下面的二行是ListAdapter的老规矩,简单吧。