How can I change the background color of list items based on the data being displayed in each item?

前端 未结 2 1196
星月不相逢
星月不相逢 2021-01-25 20:25

I have a list of orders in SQLite which vary in status: assigned, loaded, delivered. I\'d like for each of those orders, when displayed in the list, to have a different colored

相关标签:
2条回答
  • 2021-01-25 20:45

    if you are using any custom adapter for listview then, you will have a method getView(), in that just call a method before returning, and pass the view(which is returning) and data depending on you want to change the color of the row.

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view = convertView;
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.list_item_var, null);
        }
    
        TextView varView = (TextView) view.findViewById(R.id.var);
        TextView valueView = (TextView) view.findViewById(R.id.value);
    
        VarDetails var = _data.get(position);
        setRowColor(view, var.getVar());
        varView.setText(var.var);
        valueView.setText("Value: " + var.value);
    
        return view;
    }
    private void setRowColor(View view, String var) {
        if("assigned".equalsIgnoreCase(var)){
            view.setBackgroundColor(Color.rgb(255,0,0));
        }else if("loaded".equalsIgnoreCase(var)){
            view.setBackgroundColor(Color.rgb(0,255,0));
        }else if("delivered".equalsIgnoreCase(var)){
            view.setBackgroundColor(Color.rgb(0,0,255));
        }
    }
    

    please change in method depending on you data type.

    0 讨论(0)
  • 2021-01-25 21:07

    I would say try to extend CursorAdapter for binding your database with a ListView. And then you can override ListView.dispatchDraw() to customize your Paint object.

    Or maybe it's helpful to check this: Customizing Android ListView Items with Custom ArrayAdapter

    It uses different images based on weather status. Porting to your problem, you may use 9-patch or programmatically created Drawables as backgrounds, rather than changing stuff in Paint.

    0 讨论(0)
提交回复
热议问题