android – 使用SimpleCursorAdapter.ViewBinder更改TextView的颜色
作者:互联网
我正在为Android开发一个闹钟应用程序,我希望在主屏幕上显示警报列表.此ListView的每一行都在xml文件中定义.我希望每周的每一天都有单独的TextView.程序将检查sqlite db是否为例如.星期一的值= 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;
}
});
解决方法:
从SimpleCursorAdapter.ViewBinder上的Android文档:
Binds the Cursor column defined by the specified index to the
specified view. When binding is handled by this ViewBinder, this
method must return true. If this method returns false,
SimpleCursorAdapter will attempts to handle the binding on its own.
换句话说,setViewValue的实现不应该特定于任何一个View,因为SimpleCursorAdapter会在填充ListView时对每个View(根据您的实现)进行更改. setViewValue基本上是你用光标中的数据做任何你想做的事情的机会,包括设置你的视图的颜色.尝试这样的事情,
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;
}
请注意,上面的代码假定一个名为“day_of_week”的列,其中包含0-6的int值(用于指定一周中的特定日期).
标签:android,sqlite,simplecursoradapter,android-cursor,android-viewbinder 来源: https://codeday.me/bug/20190723/1513564.html