ExpandableListView继承于ListView,但是它不同于ListView,它可以有多个Group,每一个Group里都可以有多个Child。
比如可以实现QQ好友栏里类似的功能。
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
/**
* @author wing
* @date 2011/8/15
*/
public class OwnExpandableListAdapter extends BaseExpandableListAdapter {
private String[] group;
private String[][] child;
private Context context;
public OwnExpandableListAdapter(String[] group,String[][] child,Context context)
{
this.group=group;
this.child=child;
this.context=context;
}
/**
* 获取Group中的一个Child的值
*/
@Override
public Object getChild(int groupPosition, int childPosition)
{
return child[groupPosition][childPosition];
}
/**
* 获取Group中的一个Child的ID,本人没有写
*/
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
/**
* Child的视图
*/
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
//每个Group的Child,用TextView表示,当然也可以用其他的例如button之类的控件
TextView textView=new TextView(context);
textView.setText(child[groupPosition][childPosition]);
textView.setPadding(36, 0, 0, 0);
return textView;
}
/**
* 某个Group的Child的数量
*/
@Override
public int getChildrenCount(int groupPosition) {
return child[groupPosition].length;
}
@Override
public Object getGroup(int arg0) {
return null;
}
/**
* Group的数目
*/
@Override
public int getGroupCount() {
return group.length;
}
@Override
public long getGroupId(int arg0) {
return 0;
}
/**
* Group的视图
*/
@Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {
//每个Group也用TextView表示,当然也可以用其他的例如button之类的控件
TextView textView=new TextView(context);
textView.setText(group[groupPosition]);
textView.setPadding(36, 0, 0, 0);
return textView;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
}
上面是实现的一个ExpandableListAdapter,用于给ExpandableListView填充数据。
可以看见每一个Group和Child都是用的TextView。当然也可以用Button。
然后再使用。
String[]group= {"我的好友","同事"};
String[][]child= {{"张三","李四","王五"},{"赵六","杨七","嘿嘿","哈哈"}};
expandableListView.setAdapter(new OwnExpandableListAdapter(group, child, this));
另外,其实ExpandableListView也可以实现HTML中下拉框的功能。
首先介绍几个方法:
expandableListView.setDivider();这个是设定每个Group之间的分割线。
expandableListView.setGroupIndicator();这个是设定每个Group之前的那个图标。
expandableListView.collapseGroup(int group); 将第group组收起
expandableListView.expandGroup(int group); 将第group组展开
那么如何实现HTML中下拉框类似的功能呢?
由于我做的时候使用的是项目素材。不方便截图。所以就给大家一点提示。
每个Group和每个Child都使用Button,然后设定自己的样式(button selector)。
然后,每个Button都添加自己的事件,Group Button点击时,展开列表。Child Button点击时,收缩列表,并且改变Group Button的内容即可。
这样就可以实现下拉框的功能了。而且根据Button selector,基本可以定义出自己的样式。
PS:
刚毕业工作,由于项目正在测试。自己终于肯花一点时间来写写博客了。要学习的东西很多,加油!