如何进行自定义的ListView用五颜六色的项目的背景? [英] How to do custom ListView with colorful items' backgrounds?

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

问题描述

我已经创建了一个的ArrayList< HashMap的<字符串,字符串>> 收集保存我的数据的ListView 。我使用 SimpleAdapter

是否有可能改变列表项的背景下,当列表项的ID%10 == 0?

下面是code(方法生成的布局):

 私人无效fillData(){

    光标C = this.mDbManager.getNgOrderDetailByOrderNumber(this.mNumber);

    ArrayList的< HashMap的<字符串,字符串>>项目=新的ArrayList< HashMap的<字符串,字符串>>();

    如果(!c.isAfterLast()){
       做 {
           // ...填充的HashMap,并把它ArrayList中
       }而(c.moveToNext());
    }

    SimpleAdapter适配器=新SimpleAdapter(这一点,项目,R.layout.list_item,
        新的String [] {产品,有序,降价,打折},
        新的INT [] {R.id.ProductTextView,R.id.OrderedTextView,
        R.id.PriceTextView,R.id.DiscountTextView});
     ListView的L =(ListView控件)findViewById(android.R.id.list);
     l.setAdapter(适配器);
}
 

解决方案

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

例如。

 新SimpleAdapter(...){
  @覆盖
  公共查看getView(INT位置,查看convertView,ViewGroup中父){
    查看查看= super.getView(位置,convertView,父母);
    如果(位置== 10){
      //设置背景颜色=红色;
    } 其他 {
      //设置背景颜色=绿色;
    }
    返回查看;
  }
}
 

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

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

解决方案

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.

e.g.

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天全站免登陆