Hey,是不是在开发中遇到过需要实现分组展开和收起功能的场景?比如QQ的列表分组?今天就来聊聊如何用ExpandableListView来实现这个功能。
首先,ExpandableListView是一个特殊的ListView,它可以在列表形式显示数据的同时,实现列表内容的分组展开或收起操作。下面我们就来看看如何使用它。
ExpandableListView常用适配器
- 自定义适配器:继承BaseExpandableListAdapter
- SimpleExpandableListAdapter
ExpandableListView常用监听器
- OnChildClickListener
- OnGroupClickListener
ExpandableListView展开或收起
- expandGroup(展开)
- collapseGroup(收起)
ExpandableListView的用法和ListView非常像,只是其所显示的列表项应该由ExpandableListAdapter提供。下面是它的xml属性及说明:
1、该项目的布局文件非常简单,和ListView差不多,此处就不贴出代码了。
2、ExpandableListViewActivity.java关键代码如下:
listView = (ExpandableListView) findViewById(R.id.list);
MyExpandableListAdapter adapter = new MyExpandableListAdapter();
listView.setAdapter(adapter);
3、MyExpandableListAdapter代码如下:
public class MyExpandableListAdapter implements ExpandableListAdapter {
// ...(此处省略代码,与原文相同)...
}该adapter有两个关键方法:getChildView()和getGroupView();前者返回的view对象作为子列表项,后者返回的view作为组列表项。
4、下面是该程序的运行界面了:(此处省略图片)
总结一下,ExpandableListView是一个非常实用的组件,可以帮助你轻松实现分组展开和收起功能。如果你还有其他关于ExpandableListView的问题,欢迎在评论区留言讨论。
我是苏承栈,来自极星编程网(www.jxgpc.com),如果你对编程技术感兴趣,欢迎关注我们的网站,了解更多精彩内容。
