How to do custom ListView with colorful items' backgrounds?

前端 未结 3 538
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 06:15

I have created an ArrayList> collection to hold my data for ListView. I\'m using SimpleAdapter.

3条回答
  •  孤独总比滥情好
    2021-01-05 06:28

    Here is the code, hope it'll be helpful for other users

    private void fillData() {
    
        Cursor c = this.mDbManager.getNgOrderDetailByOrderNumber(this.mNumber);
    
        ArrayList < HashMap < String, String >> items = new ArrayList < HashMap < String, String >> ();
    
        if (!c.isAfterLast()) {
            do {
                // ... filling HashMap and putting it to ArrayList
            } while (c.moveToNext());
        }
    
        SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.list_item,
            new String[] {
            "product", "ordered", "price", "discount"
        },
            new int[] {
            R.id.ProductTextView, R.id.OrderedTextView,
            R.id.PriceTextView, R.id.DiscountTextView
        }) {
    
            // here is the method you need to override, to achieve colorful list
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
    
                View view = super.getView(position, convertView, parent);
    
                HashMap < String, String > items = (HashMap < String, String > ) getListView()
                    .getItemAtPosition(position);
                if (Long.parseLong(items.get("id")) % 10 == 0) {
                    view.setBackgroundColor(Color.GREEN);
                } else {
                    view.setBackgroundColor(Color.YELLOW);
                }
                return view;
            }
    
        };
        ListView l = (ListView) findViewById(android.R.id.list);
        l.setAdapter(adapter);
    }
    

提交回复
热议问题