ExpandableListView是ListView的子类,它在普通ListView的基础上进行了扩展,它把应用中的列表项分为几组,每组里又可包含多个列表项。
ExpandableListView的用法与普通ListView的用法非常相似,ExpandableListView额外常用的XML属性:
XML属性 | 说 明 |
---|---|
android:childDivider | 指定各组内各子选项之间的分隔条 |
android:groupIndicator | 显示在子列表选项旁边的Drawable对象 |
android:childIndicator | 显示在组列表选项旁边的Drawable对象 |
android:groupIndicator默认是一个三角图标,如图
你自己可以根据需求添加不同Drawable对象,以显示不同图片样式。当设置为@null时如下图:
ExpandableListView.png
同样android:childIndicator和上面一样。
下面是ExpandableListView的代码示例:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity6);
ExpandableListView list = findViewById(R.id.list);
list.setAdapter(new ExpandableListAdapter());
}
class ExpandableListAdapter extends BaseExpandableListAdapter{
private String[] armTypes = new String[]{
"神族兵种",
"虫族兵种",
"人族兵种"
};
private String[][] arms = new String[][]{
{"狂战士","龙骑士","黑暗圣堂","电兵"},
{"小狗","赤蛇","飞龙","自爆飞机",},
{"机枪兵","护士MM","幽灵"}
};
//获取指定组位置、指定子列表项处的子列表项数据
@Override
public Object getChild(int groupPosition, int childPosition) {
return arms[groupPosition][childPosition];
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition) {
return arms[groupPosition].length;
}
@Override
public Object getGroup(int groupPosition) {
return armTypes[groupPosition];
}
@Override
public int getGroupCount() {
return armTypes.length;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
//该方法决定每个子选项的外观
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View view, ViewGroup viewGroup) {
View view1 = LayoutInflater.from(context).inflate(R.layout.child_item, null);
TextView textView = view1.findViewById(R.id.textView);
textView.setText(getChild(groupPosition, childPosition).toString());
return view1;
}
//该方法决定每个组选项的外观
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup viewGroup) {
View view1 = LayoutInflater.from(context).inflate(R.layout.parent_item, null);
TextView textView = view1.findViewById(R.id.textView);
textView.setText(getGroup(groupPosition).toString());
return view1;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public boolean hasStableIds() {
return true;
}
}
上面的关键代码就是开发者自己的ExpandableListAdapter,该组件内包括如下两个关键方法:
1.getChildView:该方法返回的View对象作为子列表项。
2.getGroupView:该方法返回的View对象作为组列表项。
当然这两个方法可以借鉴ListView的Adapter中的getView方法一样优化,使列表更流畅,这里就不在重复。
网友评论