自定义SimpleAdapter(一)

本文介绍如何通过重写SimpleAdapter的getView方法来实现ListView项背景颜色的交替显示,以增强用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  学习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实例,设置它的背景颜色就可以了,还是很简单吧。
        今天写程序的时候,遇到了这个问题,特留下此贴,与大家分享。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值