ExpandableList解决方案
ExpandableListView——ExpandableListActivity及其重写方法被弃用的替代方案
今天老师上课讲到
ExpandableListActivity
的应用,但是当我们实际使用的时候,会发现它的重写方法几乎全部被弃用,其实官方也给出了相应的替代方案既然是学习,那我们就使用推荐替代方案中的
ExpandableListView
ExpandableListView官方文档:https://developer.android.com/reference/android/widget/ExpandableListView
xml
使用ExpandableListView
布局即可,关于item,自行书写,当然官方也给出了一级视图android.R.layout.simple_expandable_list_item_1
,二级视图android.R.layout.simple_expandable_list_item_2
,点开它,可以看到textView的id为text1
与text2
1 |
|
逻辑代码
数据源
需要有一级二级目录,所以定义两个数组,或者
arrayList
,map
等,无可厚非,这里我就用最偷懒的数组1
2
3private String [] provinces = {"山西省","吉林省","河北省","山东省"};
private String[][] cities = {{"太原市","吕梁市","长治市"},{"长春市","松原市","吉林市"},{"石家庄市","唐山市","承德市"},{"菏泽市","青岛市","济南市"}};自定义适配器
和
listView
,recycleView
一样,既然是列表布局,那么必然是需要适配器的,自己的适配器类继承BaseExpandableListAdapter
类,android Studio
会自动生成需要重写的方法,此方法与老师想讲的ExpandableListActivity
重写方法一致,起到学习作用大多数重写方法相信都是会的,方法名和参数很容易理解和书写,这里需要注意的是
getChildView
和getGroupView
这两个方法,其实与listView
,recycleView
一样写法一致,先进行view
的LayoutInflater
,再添加相应的数据,最后返回view
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public int getGroupCount() {
return provinces.length;
}
public int getChildrenCount(int groupPosition) {
return cities[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return provinces[groupPosition];
}
public Object getChild(int groupPosition, int childPosition) {
return cities[groupPosition][childPosition];
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public boolean hasStableIds() {
return true;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_expandable_list_item_1, null);
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(provinces[groupPosition]);
return convertView;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_item, null);
TextView textView = convertView.findViewById(R.id.text2);
textView.setText(cities[groupPosition][childPosition]);
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}活动类
在活动类中对
ExpandListView
进行findViewId
,再绑定适配器即可1
2
3
4private ExpandableListView expandableListView = null;
expandableListView = findViewById(R.id.expand_list);
expandableListView.setAdapter(myExpandListAdapter);