要實現一個可展開的列表視圖適配器,你需要使用ExpandableListView
和BaseExpandableListAdapter
ExpandableListView
。例如,在activity_main.xml
中添加以下代碼: android:id="@+id/expandableListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MyExpandableListAdapter
,并繼承BaseExpandableListAdapter
。在這個類中,你需要實現以下方法:getGroupCount()
: 返回分組的數量。getChildrenCount(int groupPosition)
: 返回指定分組中子項的數量。getGroup(int groupPosition)
: 返回指定分組的數據。getChild(int groupPosition, int childPosition)
: 返回指定子項的數據。getGroupId(int groupPosition)
: 返回分組的ID。getChildId(int groupPosition, int childPosition)
: 返回子項的ID。hasStableIds()
: 返回是否使用穩定的ID。getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
: 返回分組的視圖。getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
: 返回子項的視圖。isChildSelectable(int groupPosition, int childPosition)
: 返回子項是否可選。MyExpandableListAdapter
類中,實現上述方法。例如:public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// ... 其他代碼
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return groups.get(groupPosition).getChildren().size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition).getChildren().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) {
// 實現分組視圖
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// 實現子項視圖
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity
中設置適配器:public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private MyExpandableListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandableListView);
adapter = new MyExpandableListAdapter();
expandableListView.setAdapter(adapter);
}
}
MyExpandableListAdapter
類中的getGroupView()
和getChildView()
方法中實現。