我有一个使用SimpleCursorAdapter从SQLite数据库填充的列表视图。在游标中返回的一个列是整数值0或1.在我的列表视图中,我想以更友好的形式显示它(即“是”或“否”)并且可能使用不同的文本颜色为每个人。这是我的来源:
Cursor c = dbHelper.fetchAllItems();
startManagingCursor(c);
String[] from = {"deployed", "designation", "serial"};
int[] to = {R.id.deployed, R.id.designation, R.id.serial};
setListAdapter(new SimpleCursorAdapter(this, R.layout.list_item, c, from, to));
当SimpleCursorAdapter将每个视图简单地映射到列名时,如何有条件地切换布局中的元素和/或属性。 (假设我不能使用SimpleCursorAdapter来完成此操作,这是安全的吗?)
答案 0 :(得分:3)
通过添加自定义适配器,扩展CursorAdapter
来解决修饰:
Cursor c = dbHelper.fetchAllItems();
startManagingCursor(c);
setListAdapter(new RowAdapter(this, c));
新嵌套类:
private static class RowAdapter extends CursorAdapter {
public RowAdapter(Context context, Cursor c) {
super(context, c);
}
public void bindView(View view, Context context, Cursor c) {
TextView vDesignation = (TextView) view.findViewById(R.id.designation);
TextView vSerial = (TextView) view.findViewById(R.id.serial);
TextView vDeployed = (TextView) view.findViewById(R.id.deployed);
String designation = c.getString(c.getColumnIndexOrThrow("designation"));
String serial = c.getString(c.getColumnIndexOrThrow("serial"));
int deployed = c.getInt(c.getColumnIndexOrThrow("deployed"));
vDesignation.setText(designation);
vSerial.setText(serial);
vDeployed.setText(deployed > 0 ? R.string.yes : R.string.no);
vDeployed.setTextColor(deployed > 0 ? view.getResources().getColor(R.color.yes) : view.getResources().getColor(R.color.no));
}
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item, parent, false);
bindView(view, context, c);
return view;
}
}