我正在使用expandablelistview。无论如何我可以在单击里面的图像时展开组行?我知道要让图像响应点击,我必须设置它的焦点。现在,一旦此图像响应click(在我的客户适配器内),我如何以编程方式扩展/折叠它所属的特定组行?
谢谢
答案 0 :(得分:13)
在适配器
中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 :(得分:3)
更简单的方法:
ExpandableListView
; 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;
}
在您的活动onCreate()
或片段onCreateView()
中
ExpandableListView listView = (ExpandableListView) view.findViewById(R.id.expandable_list_view);
mAdapter = new YourAdapter(listView);
listView.setAdapter(mAdapter);
答案 2 :(得分:0)
这不会回答OP中的问题,但是我最终在这里找到了一种方法,只有在适配器加载了项目之后,才能以编程方式扩展组,这是我的解决方法:
MyAdapter adapter = new MyAdapter(this, viewModel);
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
if (adapter.getGroupCount()>0) {
binding.expandableListView.expandGroup(0);
}
}
});
binding.expandableListView.setAdapter(adapter);