但我想要的是只有第 4 项有孩子并且可以扩展
如果 Item 没有子项,则不会扩展。你可以像这样的图像:
public class Item {
private String title;
private List<Option> children; // if size = 0 won't be expanded
}
这是ExpandableListView 的本机行为,因此如果任何 Item 没有子项,则隐式不会展开,但您需要为组(Items)和子项(Options)设置 OnClickListener:
public boolean onChildClick(ExpandableListView parent, View row,
int groupPosition, int childPosition, long id) {
// callback method after click for Options
return false;
}
public boolean onGroupClick(ExpandableListView parent, View row,
int groupPosition, long id) {
/** if you are using BaseAdapter subclass implementation **/
adapter.getGroup(groupPosition)).getChildren() == null) {
// item doesn't have children
}
else {
// has children
}
一般来说,如果您想更好地控制您的 ListView,我非常建议您在您的情况下实现自己的 ListAdapter 子类,您可以使用BaseExpandableListAdapter。
List 的出现只是关于正确样式布局的问题,例如删除组指示器
android:groupIndicator="@null"
更新:
@Roberto Lombardini 提到的问题:
这个解决方案的一个小问题是小灰色三角形
指示组视图的状态(扩展与否)将出现
即使组没有孩子。我错了吗?
如果您只想为带有子项的项目设置灰色三角形,则需要在您的自定义适配器中使用getGroupView() 方法修复它:
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// inflating View etc.
Item item = items.get(groupPosition);
if (item != null) {
// if Item has children
if (item.getChildren() != null && !item.getChildren().isEmpty()) {
// set children indicator to VISIBLE
imageView.setVisibility(ImageView.VISIBLE);
}
// if Item doesn't have children
else {
// set children indicator to GONE
imageView.setVisibility(ImageView.GONE);
}
}
}