Android 分组listview 简易实现方法

原文链接:http://codesblock.com/?p=111

在Android开发中,listview成为activity非常常用的基本组件之一,但是需求往往比较复杂,listview需要承载的数据往往有多种表现形式。

有些需求更是需要scrollview中嵌套listview才能很好的实现,但是Android并没有提供一个合理的scrollview中嵌套listview的解决方案。

在scrollview中嵌套listview会导致listview的高度无法正确计算。就算使用常用的解决方案--根据listview的内容动态设置listview的高度,仍然会导致一个最严重的问题--由于listview的touch事件被scrollview吃掉了,listview中的子view无法再重用,listview的优势荡然无存。

我通过继承了BaseAdapter实现了一个AbsGroupListAdapter,使用最简易的方法实现多分组的listview实现。使用非常简单,只要继承AbsGroupListAdapter,并重写getChildView方法,就可以实现分组显示不同的view.

class GroupAdapter extends AbsGroupAdapter {

public GroupAdapter(Context context) {
super(context);
}

@Override
public View getChildView(View probableView, int groupIndex, int childIndex, int position, ViewGroup parent) {
switch (groupIndex) {
case 0://根据组别返回不同的view,并且view可高度复用,每个组别下发的probableview类型都是相应组别的使用过的view类型
TextView view = null;
if (probableView != null) {
view = (TextView) probableView;
} else {
view = new TextView(mContext);
}
view.setText("position:" + childIndex);
return view;
case 2:
ImageView view2 = null;
if (probableView != null) {
view2 = (ImageView) probableView;
} else {
view2 = new ImageView(mContext);
}
view2.setImageResource(android.R.drawable.ic_dialog_email);
return view2;
case 3:
Button button = null;
if (probableView != null) {
button = (Button) probableView;
} else {
button = new Button(mContext);
}
button.setText("button:" + childIndex);
return button;
default:
break;
}
return null;
}

}

为listview设置这个adapter也非常简单,只需要几行代码就能实现分组功能

ListView listView = (ListView) findViewById(R.id.listview);
        final GroupAdapter adapter = new GroupAdapter(getApplicationContext());
        adapter.bindListView(listView); //重要,为adapter绑定listview
        listView.setAdapter(adapter); //与普通adapter相同
       
        adapter.addGroup(10); // add a group 增加一个组,只需要输入组的内容数量就可以添加了
        final ImageView image = new ImageView(getApplicationContext());
        image.setImageResource(R.drawable.image);
        adapter.addStableView(image); // add a view 这个方法可以添加一个固定的view,这个view不可以复用到listview中的其他内容中。
        adapter.addGroup(10); // add a group
        adapter.addGroup(10); // add a group
        adapter.notifyDataSetChanged();

如图所示,此listview共分为3个组,组一是textview、组二是一张图片、组三是imageview。

源码已经上传到github中,可以随便下载源码和demo。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值