如何使用彩色项目的背景自定义 ListView? [英] How to do custom ListView with colorful items' backgrounds?

查看:31
本文介绍了如何使用彩色项目的背景自定义 ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 ArrayList> 集合来保存 ListView 的数据.我正在使用 SimpleAdapter.

I have created an ArrayList<HashMap<String, String>> collection to hold my data for ListView. I'm using SimpleAdapter.

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

Is it possible to change background of list item when list item's ID % 10 == 0?

这是代码(方法生成布局):

Here is the code (method generating layout):

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

推荐答案

你覆盖了 getView 在您的适配器中对视图进行更改.请记住,ListView 重用了视图实现,因此如果您将颜色更改为第 10 项,请确保将所有其他视图的颜色设置为相反.

You override getView in your adapter to make changes to the view. Keep in mind that ListView reuses the view implementations, so if you change the color to item 10, make sure you set the color to the opposite for all other views.

例如

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

这篇关于如何使用彩色项目的背景自定义 ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆