我正在为android开发一个闹钟应用程序,我想在主屏幕上显示闹钟列表。这ListView
的每一行都在xml文件中定义。我想一周中的每一天都有单独的TextViews
。如果monday
的值为1,程序将签入sqlite db,然后将此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文档:
将指定索引定义的游标列绑定到
指定的视图。当这个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;
}
注意,上面的代码假设有一个名为
"day_of_week"
的列,该列包含int
值0-6(以指定一周中的特定日期)。关于android - 使用SimpleCursorAdapter.ViewBinder更改TextView的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9658201/