This solution works for me (expandable list view used inside navigation view):
创建自定义菜单模型,例如:
public class DrawerExpandedMenuModel {
String iconName = "";
int id = -1;
int iconImg = -1;
boolean isSelected = false;
.
.
.
重写ExpandableListView的onChildClick方法
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
for (int k = 0; k < listDataHeader.size(); k++){
listDataHeader.get(k).isSelected(false);
if (listDataChild.containsKey(listDataHeader.get(k))) {
List<DrawerExpandedMenuModel> childList = listDataChild.get(listDataHeader.get(k));
if (childList != null) {
for (int j = 0; j < childList.size(); j++) {
if (k == groupPosition && j == childPosition) {
childList.get(j).isSelected(true);
} else {
childList.get(j).isSelected(false);
}
}
}
}
}
mMenuAdapter.notifyDataSetChanged();
覆盖 ExpandableListView 的 onGroupClick 方法。
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
for (int k = 0; k < listDataHeader.size(); k++){
if (k == groupPosition) {
listDataHeader.get(k).isSelected(true);
} else {
listDataHeader.get(k).isSelected(false);
}
if (listDataChild.containsKey(listDataHeader.get(k))) {
List<DrawerExpandedMenuModel> childList = listDataChild.get(listDataHeader.get(k));
if (childList != null) {
for (int j = 0; j < childList.size(); j++) {
childList.get(j).isSelected(false);
}
}
}
}
mMenuAdapter.notifyDataSetChanged();
覆盖 getGroupView 和 getChildView 方法。
public class DrawerExpandableListAdapter extends BaseExpandableListAdapter {
.
.
.
@Override
public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, final ViewGroup parent) {
if (headerTitle.isSelected() == true) convertView.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
else convertView.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
.
.
.
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (childObj.isSelected() == true) convertView.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
else convertView.setBackgroundColor(mContext.getResources().getColor(R.color.transparent));
就是这样!