Expand group row programmatically in expandable list
In adapter
private OnItemSelectedListener onItemSelectedCallback;
public interface OnItemsSelectedListener {
public void onImageSelected(int groupPos);
}
public YourAdapter(Context context) {
try {
this.onItemSelectedCallback = (OnItemSelectedListener ) context;
}
catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnItemSelectedListener ");
}
}
Add this in getView()
ImageView imageView = new ImageView();
imageView.setTag(R.id.tagGroupPosition, groupPosition);
imageView.setOnClickListener(onClickListener);
Add this in OnClickListener
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
int groupPos = ((ImageView) v).getTagId(R.id.tagGroupPosition);
onItemSelectedCallback.onImageSelected(groupPos);
}
}
Then in activity you have to implements YourAdapter.OnItemsSelectedListener the Override onImageSelected
@Override
public void onImageSelected(int groupPos){
if(expandableList.isGroupExpanded(groupPos)){
expandableList.collapseGroup(groupPos);
}else{
expandableList.expandGroup(groupPos);
}
}
A simpler way:
- Pass a reference to the
ExpandableListView
in the adapter constructor; - in
getGroupView
add anOnClickListener
on the button you need and simply calllistView.expandGroup(position);
Example:
public class YourAdapter extends BaseExpandableListAdapter {
private ExpandableListView listView;
public ReportsAdapter(ExpandableListView listView) {
this.listView = listView;
}
//...
@Override
public View getGroupView(final int position, boolean isExpanded, View convertView, ViewGroup parent) {
ParentViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_item, parent, false);
holder = new ParentViewHolder();
//... holder logic
holder.btnExpand = convertView.findViewById(R.id.btn_expand);
convertView.setTag(holder);
} else {
holder = (ParentViewHolder) convertView.getTag();
}
//..holder logic
holder.btnExpand.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listView.expandGroup(position);
}
});
return convertView;
}
In your Activity onCreate()
or Fragment onCreateView()
have
ExpandableListView listView = (ExpandableListView) view.findViewById(R.id.expandable_list_view);
mAdapter = new YourAdapter(listView);
listView.setAdapter(mAdapter);