blu*_*wel 3 sqlite android simplecursoradapter android-cursor android-viewbinder
我正在为Android开发一个闹钟应用程序,我希望在主屏幕上显示警报列表.其中的每一行都ListView在xml文件中定义.我希望TextViews每周的每一天都能分开.程序将检查sqlite db是否为例如.mondayis = 1的值,然后将其颜色更改TextView为红色.我写了这段代码,但这不起作用.怎么了?
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllAlarms();
startManagingCursor(c);
String[] from = new String[] { db.KEY_TIME, db.KEY_NAME };
int[] to = new int[] { R.id.time, R.id.alarmName };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter alarms =
new SimpleCursorAdapter(this, R.layout.alarm_row, c, from, to);
alarms.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int dayOfWeekIndex = cursor.getColumnIndex("mon");
if (dayOfWeekIndex == columnIndex) {
int color = cursor.getInt(dayOfWeekIndex);
switch(color) {
case 0: ((TextView) view).setTextColor(Color.RED); break;
case 1: ((TextView) view).setTextColor(Color.GRAY); break;
}
return true;
}
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
从Android文档SimpleCursorAdapter.ViewBinder:
将指定索引定义的Cursor列绑定到指定视图.当此ViewBinder处理绑定时,此方法必须返回true.如果此方法返回false,SimpleCursorAdapter将尝试自行处理绑定.
换句话说,您的实现setViewValue不应该特定于任何一个View,因为它SimpleCursorAdapter会View在填充时对每个实现(根据您的实现)进行更改ListView.setViewValue基本上你有机会根据你的数据做任何你想做的事情Cursor,包括设置你的观点的颜色.尝试这样的事情,
public boolean setViewValue(View view, Cursor cursor, int columnIndex){
// if this holds true, then you know that you are currently binding text to
// the TextView with id "R.id.alarmName"
if (view.getId() == R.id.alarmName) {
final int dayOfWeekIndex = cursor.getColumnIndex("day_of_week");
final int color = cursor.getInt(dayOfWeekIndex);
switch(color) {
case 0: ((TextView) view).setTextColor(Color.RED); break;
case 1: /* ... */ break;
case 2: /* ... */ break;
/* etc. */
}
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是上面的代码假定一个名为列"day_of_week"其持有int价值0-6(指定一周的某一天).