自定义Adapter,通过复写getView方法,实现ListView中item背景颜色变化

来源:互联网 发布:渡边直美自创品牌淘宝 编辑:程序博客网 时间:2024/05/18 02:28
学习Android编程的各位同学,如果用过listView的话,应该一定知道SimpleAdapter吧,但是系统自带的SimpleAdapter功能有限,有事无法满足我们的需求,这就需要我们来自定义属于自己的SimpleAdapter。举个简单的小例子,就是实现列表背景颜色的交替。效果如下:

自定义SimpleAdapter(一) - 哼哈二将 - 尚武思文
下面讲讲我是如何实现的。
        其实很简单,就是重载SimpleAdapter的getView函数。代码如下:
public class AltColorAdapter extends SimpleAdapter {

    
private static int[] mColors = { R.drawable.grey, R.drawable.white };
    
    
public AltColorAdapter(Context context,
            List
<? extends Map<String, ?>> data, int resource, String[] from,
            
int[] to) {
        
super(context, data, resource, from, to);
        
// TODO Auto-generated constructor stub
    }

    @Override
    
public View getView(int position, View convertView, ViewGroup parent) {
        
// TODO Auto-generated method stub
        int[] arrayOfInt = mColors;
        
int colorLength = mColors.length;
        
int selected = arrayOfInt[position % colorLength];
        View localView 
= super.getView(position, convertView, parent);
        localView.setBackgroundResource(selected);
        
return localView;
    }
}
        定义一个int型数组mColors,保存想要显示的所有颜色。 在getView函数中,我们知道现在显示的item的position,利用position % colorLength就可以求出item项对应的颜色。然后利用系统的super.getView(position, convertView, parent)函数获得View实例,设置它的背景颜色就可以了,还是很简单吧。
        今天写程序的时候,遇到了这个问题,特留下此贴,与大家分享。
原创粉丝点击