ExpandableListView(可折叠列表)的基本使用

时间:2022-08-09 19:41:49

本节引言:

本节要讲解的Adapter类控件是ExpandableListView,就是可折叠的列表,它是ListView的子类, 在ListView的基础上它把应用中的列表项分为几组,每组里又可包含多个列表项。至于样子, 类似于QQ联系人列表,他的用法与ListView非常相似,只是ExpandableListVivew显示的列表项 需由ExpandableAdapter提供。 下面我们来学习这个控件的基本使用! 官方API:ExpandableListView

这里需要说明一下:原生的ExpandableListView是不支持动画效果的,如果想实现动画效果建议使用GIT上的开源控件,参考文章:点击打开链接


1.相关属性

  • android:childDivider:指定各组内子类表项之间的分隔条,图片不会完全显示, 分离子列表项的是一条直线
  • android:childIndicator:显示在子列表旁边的Drawable对象,可以是一个图像
  • android:childIndicatorEnd:子列表项指示符的结束约束位置
  • android:childIndicatorLeft:子列表项指示符的左边约束位置
  • android:childIndicatorRight:子列表项指示符的右边约束位置
  • android:childIndicatorStart:子列表项指示符的开始约束位置
  • android:groupIndicator:显示在组列表旁边的Drawable对象,可以是一个图像
  • android:indicatorEnd:组列表项指示器的结束约束位置
  • android:indicatorLeft:组列表项指示器的左边约束位置
  • android:indicatorRight:组列表项指示器的右边约束位置
  • android:indicatorStart:组列表项指示器的开始约束位置

2.实现ExpandableAdapter的三种方式

1. 扩展BaseExpandableListAdpter实现ExpandableAdapter。

2. 使用SimpleExpandableListAdpater将两个List集合包装成ExpandableAdapter

3. 使用simpleCursorTreeAdapter将Cursor中的数据包装成SimpleCuroTreeAdapter 本节示例使用的是第一个,扩展BaseExpandableListAdpter,我们需要重写该类中的相关方法, 下面我们通过一个代码示例来体验下!


3.代码示例

我们来看下实现的效果图

ExpandableListView(可折叠列表)的基本使用

下面我们就来实现上图的这个效果:

核心是重写BaseExpandableListAdpter,其实和之前写的普通的BaseAdapter是类似的, 但是BaseExpandableListAdpter则分成了两部分:组和子列表,具体看代码你就知道了!

另外,有一点要注意的是,重写isChildSelectable()方法需要返回true,不然不会触发 子Item的点击事件!下面我们来写写:

首先是组和子列表的布局:

item_exlist_group.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp">

<TextView
android:id="@+id/tv_group_name"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:text="AP"
android:textStyle="bold"
android:textSize="20sp" />

</LinearLayout>

item_exlist_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp"
android:background="#6BBA79">

<ImageView
android:id="@+id/img_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@mipmap/iv_lol_icon1"
android:focusable="false"/>

<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:focusable="false"
android:text="提莫"
android:textSize="18sp" />

</LinearLayout>

然后是自定义的Adapter类:

MyBaseExpandableListAdapter.java

/**
* Created by Jay on 2015/9/25 0025.
*/

public class MyBaseExpandableListAdapter extends BaseExpandableListAdapter {

private ArrayList<Group> gData;
private ArrayList<ArrayList<Item>> iData;
private Context mContext;

public MyBaseExpandableListAdapter(ArrayList<Group> gData,ArrayList<ArrayList<Item>> iData, Context mContext) {
this.gData = gData;
this.iData = iData;
this.mContext = mContext;
}

@Override
public int getGroupCount() {
return gData.size();
}

@Override
public int getChildrenCount(int groupPosition) {
return iData.get(groupPosition).size();
}

@Override
public Group getGroup(int groupPosition) {
return gData.get(groupPosition);
}

@Override
public Item getChild(int groupPosition, int childPosition) {
return iData.get(groupPosition).get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}

@Override
public boolean hasStableIds() {
return false;
}

//取得用于显示给定分组的视图. 这个方法仅返回分组的视图对象
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

ViewHolderGroup groupHolder;
if(convertView == null){
convertView
= LayoutInflater.from(mContext).inflate(
R
.layout.item_exlist_group, parent, false);
groupHolder
= new ViewHolderGroup();
groupHolder
.tv_group_name = (TextView) convertView.findViewById(R.id.tv_group_name);
convertView
.setTag(groupHolder);
}else{
groupHolder
= (ViewHolderGroup) convertView.getTag();
}
groupHolder
.tv_group_name.setText(gData.get(groupPosition).getgName());
return convertView;
}

//取得显示给定分组给定子位置的数据用的视图
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ViewHolderItem itemHolder;
if(convertView == null){
convertView
= LayoutInflater.from(mContext).inflate(
R
.layout.item_exlist_item, parent, false);
itemHolder
= new ViewHolderItem();
itemHolder
.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
itemHolder
.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
convertView
.setTag(itemHolder);
}else{
itemHolder
= (ViewHolderItem) convertView.getTag();
}
itemHolder
.img_icon.setImageResource(iData.get(groupPosition).get(childPosition).getiId());
itemHolder
.tv_name.setText(iData.get(groupPosition).get(childPosition).getiName());
return convertView;
}

//设置子列表是否可选中
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}


private static class ViewHolderGroup{
private TextView tv_group_name;
}

private static class ViewHolderItem{
private ImageView img_icon;
private TextView tv_name;
}

}

PS:存储子列表的数据不一定要用ArrayList<ArrayList>这种,根据自己的需求 定义~

最后是MainActivity的布局以及Java代码:

布局文件:activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".MainActivity">

<ExpandableListView
android:id="@+id/exlist_lol"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:childDivider="#E02D2F"/>

</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private ArrayList<Group> gData = null;
private ArrayList<ArrayList<Item>> iData = null;
private ArrayList<Item> lData = null;
private Context mContext;
private ExpandableListView exlist_lol;
private MyBaseExpandableListAdapter myAdapter = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView
(R.layout.activity_main);
mContext
= MainActivity.this;
exlist_lol
= (ExpandableListView) findViewById(R.id.exlist_lol);


//数据准备
gData
= new ArrayList<Group>();
iData
= new ArrayList<ArrayList<Item>>();
gData
.add(new Group("AD"));
gData
.add(new Group("AP"));
gData
.add(new Group("TANK"));

lData
= new ArrayList<Item>();

//AD组
lData
.add(new Item(R.mipmap.iv_lol_icon3,"剑圣"));
lData
.add(new Item(R.mipmap.iv_lol_icon4,"德莱文"));
lData
.add(new Item(R.mipmap.iv_lol_icon13,"男枪"));
lData
.add(new Item(R.mipmap.iv_lol_icon14,"韦鲁斯"));
iData
.add(lData);
//AP组
lData
= new ArrayList<Item>();
lData
.add(new Item(R.mipmap.iv_lol_icon1, "提莫"));
lData
.add(new Item(R.mipmap.iv_lol_icon7, "安妮"));
lData
.add(new Item(R.mipmap.iv_lol_icon8, "天使"));
lData
.add(new Item(R.mipmap.iv_lol_icon9, "泽拉斯"));
lData
.add(new Item(R.mipmap.iv_lol_icon11, "狐狸"));
iData
.add(lData);
//TANK组
lData
= new ArrayList<Item>();
lData
.add(new Item(R.mipmap.iv_lol_icon2, "诺手"));
lData
.add(new Item(R.mipmap.iv_lol_icon5, "德邦"));
lData
.add(new Item(R.mipmap.iv_lol_icon6, "奥拉夫"));
lData
.add(new Item(R.mipmap.iv_lol_icon10, "龙女"));
lData
.add(new Item(R.mipmap.iv_lol_icon12, "狗熊"));
iData
.add(lData);

myAdapter
= new MyBaseExpandableListAdapter(gData,iData,mContext);
exlist_lol
.setAdapter(myAdapter);

//为列表设置点击事件
exlist_lol
.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(mContext, "你点击了:" + iData.get(groupPosition).get(childPosition).getiName(), Toast.LENGTH_SHORT).show();
return true;
}
});


}
}
1. 设置ExpandableListView 默认是展开的: 
先实例化exListView 然后 

[java] view plain copy
  1. exListView.setAdapter(exlvAdapter);   
  2. //遍历所有group,将所有项设置成默认展开  
  3.  intgroupCount = exListView.getCount();   
  4. for (inti=0; i<groupCount; i++)  
  5.  {   
  6.        exListView.expandGroup(i);  
  7.  };   


2. 去掉ExpandableListView 默认的箭头 
用到ExpandableListView时有个箭头图标系统自带的在你自定义布局也不能去掉只要设置一个属性即可,如下: 
settingLists.setGroupIndicator(null); ~~~~~~~~~~~~~~~~~此处就是设置自定义的箭头图标的。置空则没有了。  
也可以自定义(但是位置还是在那个地方不推荐)如下: 
首先,自定义一个expandablelistviewselector.xml文件,具体内容如下: Java代码 
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">   
  3.      <item android:state_expanded="true" android:drawable="@drawable/expandablelistviewindicatordown" />   
  4.       <item android:drawable="@drawable/expandablelistviewindicator" />  
  5.  </selector>   

加一句代码如下: 

[java] view plain copy
  1. settingLists.setGroupIndicator(this.getResources().getDrawable(R.layout.expandablelistviewselector));    
  2. 或xml设置:  
  3.     android:groupIndicator="@drawable/groupIndicator_selector"  


大功告成 


3. 将默认的箭头修改到右边显示: 
 
1首先ExpandableListViewelistview;  

elistview.setGroupIndicator(null);//将控件默认的左边箭头去掉,

 2在自定义的继承自BaseExpandableListAdapter的adapter中有一个方法

[java] view plain copy
  1. /** * 父类view */ @Override   
  2. ublic View getGroupView(intgroupPosition, booleanisExpanded, View convertView, ViewGroup parent)  
  3. { Log.i("zhaoxiong","parent view");   
  4.      LinearLayoutparentLayout=(LinearLayout) View.inflate(context, R.layout.wowocoupons_parent_item, null);   
  5.     TextViewparentTextView=(TextView)parentLayout.findViewById(R.id.parentitem);  
  6.     parentTextView.setText(parentlist.get(groupPosition));   
  7.     ImageViewparentImageViw=(ImageView) parentLayout.findViewById(R.id.arrow);   
  8.     //判断isExpanded就可以控制是按下还是关闭,同时更换图片  
  9.    if(isExpanded){   
  10.        parentImageViw.setBackgroundResource(R.drawable.arrow_down);   
  11.     }else{   
  12.         parentImageViw.setBackgroundResource(R.drawable.arrow_up); }    
  13.      return parentLayout;  
  14. }  

expandablelistview响应onGroupClick监听:设置expandablelistview.setOnGroupClickListener()
折叠和展开事件,可以设置setOnGroupCollapseListener和setOnGroupExpandListener


ExpandableListView中包含多个group,想要展开一个group时,其他group都关闭:
[java] view plain copy
  1. exList.setOnGroupExpandListener(new OnGroupExpandListener() {    
  2.     
  3.         @Override    
  4.         public void onGroupExpand(int groupPosition) {    
  5.             for (int i = 0; i < getData().size(); i++) {    
  6.                 if (groupPosition != i) {    
  7.                     exList.collapseGroup(i);    
  8.                 }    
  9.             }    
  10.     
  11.         }    
  12.     
  13.     });  
3.expandablelistview的Group点击事件,onGroupClick的返回值false展开,true不展开

[java] view plain copy
  1.          tt_list.setOnGroupClickListener(new OnGroupClickListener() {  
  2.               
  3.             @Override  
  4.             public boolean onGroupClick(ExpandableListView parent, View v,  
  5.                     int groupPosition, long id) {  
  6.                 IsFlag=true;  
  7.   
  8.                 if(adapter.getGroupData().get(groupPosition).getList().size()==1){  
  9.                     Bundle b=new Bundle();  
  10.                     b.putInt("saveIndex"0);  
  11. //                  b.putString("mac", mac);  
  12. //                  b.putString("deviceId", mDeviceId);  
  13.                     b.putSerializable("datalist", adapter.getGroupData().get(groupPosition).getList());  
  14.                     Intent i=new Intent(WappushBindingActivity.this,VideoPlayerActivity.class);  
  15.                     i.putExtras(b);   
  16.                     startActivity(i);  
  17.                 }  
  18. //              int groupCount = tt_list.getCount();     
  19. //              for (int i=0; i<groupCount; i++){     
  20. //                  if(i!=GroupPosition)  
  21. //                      tt_list.collapseGroup(i);    
  22. //               };   
  23. //              Log.v("xulongheng*WappushBind*tt_list", "onGroupClick:"+previousX+"/"+previousY);  
  24.                 return true;   //默认为false,设为true时,点击事件不会展开Group  
  25.             }  
  26.         });