如何制作自定义ListView,使其具有彩色项目背景?

8

我创建了一个 ArrayList<HashMap<String, String>> 集合来保存我的数据,以供 ListView 使用。我正在使用 SimpleAdapter

当列表项的 ID % 10 == 0 时,是否可以更改列表项的背景?

以下是生成布局的代码(方法):

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 });
     ListView l = (ListView) findViewById(android.R.id.list);
     l.setAdapter(adapter);
}
3个回答

8
你需要在适配器中重写getView来更改视图。请记住,ListView会重复使用视图实现,因此如果你将颜色更改为第10项,请确保为所有其他视图设置相反的颜色。
例如:
new SimpleAdapter( ... ) {
  @Override
  public View getView (int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    if (position == 10) {
      // set background color = red;
    } else {
      // set background color = green;
    }
    return view;
  }
}

3

以下是代码,希望对其他用户有所帮助。

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);
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接