我在 SQLite 中有一个订单列表,其状态各不相同:已分配、已加载、已交付。我希望每个订单在列表中显示时都有不同的颜色背景。到目前为止,我还没有找到一个好的方法来做到这一点。
我发现了很多关于如何根据位置更改列表项的背景颜色的讨论,但没有一个是根据数据内容进行的。我还发现了很多关于如何更改用于突出显示所选项目的颜色的讨论。这些对我没有帮助。
我提出的解决问题的唯一方法包括在适配器创建列表后运行整个列表,并为每个项目设置背景。这是笨拙和浪费的。我希望有一种更有效的方法,可以在从光标创建列表时更改适配器中的背景。
我确信有更好的方法。我对 Android 还太陌生,不了解它。
我非常感谢迄今为止的回应。我正在尽力将它们纳入其中,但仍然没有成功。这是我刚刚尝试过的,基于我得到的答案和我所做的研究。
public class OrderListAdapter extends SimpleCursorAdapter {
private static final String TAG = "SimpleCursorAdapter";
Context _context = null;
int layoutResourceId = 0;
public OrderListAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
_context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
String tag = TAG + ".getView()";
Log.d(tag,"in getView()");
if (view == null) {
LayoutInflater inflater = ((Activity)_context).getLayoutInflater();
view = inflater.inflate(R.layout.fragment_order_list_row, null);
}
setRowColor(view);
return view;
}
private void setRowColor(View view) {
String tag = TAG + ".setRowColor()";
Cursor cursor = getCursor();
int col = cursor
.getColumnIndex(DBContract.DeliveryOrderTable.ENROUTE_FLAG);
String enroute_flag = cursor.getString(col);
Log.d(tag, "enroute_flag = [" + enroute_flag + "]");
col = cursor
.getColumnIndex(DBContract.DeliveryOrderTable.DELIVERED_DATETIME);
String deliveredDateStr = cursor.getString(col);
Log.d(tag, "deliveredDateStr = [" + deliveredDateStr + "]");
int bgColorId = 0;
if (!deliveredDateStr.equals("")) {
bgColorId = R.color.bg_status_delivered_color;
Log.d(tag, "Setting to delivered color");
} else if (enroute_flag.startsWith("T") || enroute_flag.startsWith("Y")) {
Log.d(tag, "Setting to enroute color");
bgColorId = R.color.bg_status_enroute_color;
} else {
Log.d(tag, "Setting to assigned color");
bgColorId = R.color.bg_status_assigned_color;
}
view.setBackgroundColor(_context.getResources().getColor(bgColorId));
}
}
不幸的是,这不起作用。如果我不调用 super.getView(),显然,我会在字段中没有数据,因为我没有明确进行传输,但我认为我可以修改返回的视图。
我的痕迹显示我正在读取数据,但背景颜色没有改变。
看来我试图更改的视图是 LinearLayout,但更改背景颜色似乎不起作用。
知道了!确保所有子视图的背景都是透明的。