在可扩展列表中以编程方式展开组行

我正在使用expandablelistview。 无论如何我可以在单击里面的图像时展开组行? 我知道要让图像响应点击,我必须设置它的焦点。 现在,一旦此图像响应click(在我的客户适配器内),我如何以编程方式扩展/折叠它所属的特定组行?

谢谢

在适配器中

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 "); } } 

在getView()中添加

 ImageView imageView = new ImageView(); imageView.setTag(R.id.tagGroupPosition, groupPosition); imageView.setOnClickListener(onClickListener); 

在OnClickListener中添加它

 OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { int groupPos = ((ImageView) v).getTagId(R.id.tagGroupPosition); onItemSelectedCallback.onImageSelected(groupPos); } } 

然后在活动中你必须实现YourAdapter.OnItemsSelectedListener Override onImageSelected

 @Override public void onImageSelected(int groupPos){ if(expandableList.isGroupExpanded(groupPos)){ expandableList.collapseGroup(groupPos); }else{ expandableList.expandGroup(groupPos); } } 

一种更简单的方法:

  1. 在适配器构造函数中传递对ExpandableListView的引用;
  2. getGroupView ,在你需要的按钮上添加一个OnClickListener ,只需调用listView.expandGroup(position);

例:

 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; } 

在你的Activity onCreate()或Fragment onCreateView()

 ExpandableListView listView = (ExpandableListView) view.findViewById(R.id.expandable_list_view); mAdapter = new YourAdapter(listView); listView.setAdapter(mAdapter);