Android 三级ExpandableListView点击子项获取所有父级名称实现方法
实现方法
你可以通过透传一级父节点名称到二级适配器的方式,直接在子项点击事件中拿到所有上级节点名称,修改步骤如下:
步骤1:修改SecondLevelAdapter新增成员变量和构造参数
在SecondLevelAdapter中新增一级父节点名称的成员变量,调整构造函数接收该参数:
public class SecondLevelAdapter extends BaseExpandableListAdapter { private Context context; List<String[]> data; String[] headers; ImageView ivGroupIndicator; // 新增:存储当前二级列表对应的一级父节点名称 private String firstLevelParentName; // 调整构造函数,新增一级父名称参数 public SecondLevelAdapter(Context context, String[] headers, List<String[]> data, String firstLevelParentName) { this.context = context; this.data = data; this.headers = headers; this.firstLevelParentName = firstLevelParentName; } // 其余原有代码保持不变
步骤2:修改ThreeLevelListAdapter中二级适配器的初始化逻辑
在ThreeLevelListAdapter的getChildView方法中,创建SecondLevelAdapter实例时,把当前一级节点的名称传入:
// 原有代码 // secondLevelELV.setAdapter(new SecondLevelAdapter(context, headers, childData)); // 修改为:传入当前一级父节点名称 secondLevelELV.setAdapter(new SecondLevelAdapter(context, headers, childData, parentHeaders[groupPosition]));
步骤3:在子项点击事件中获取所有父级名称
修改SecondLevelAdapter的getChildView中的点击事件逻辑,直接取存储的一级父名称和当前二级父名称即可:
@Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.row_third, null); TextView textView = convertView.findViewById(R.id.rowThirdText); String[] childArray = data.get(groupPosition); String text = childArray[childPosition]; textView.setText(text); textView.setOnClickListener(v -> { // 一级父级名称 String firstParent = firstLevelParentName; // 二级父级名称 String secondParent = headers[groupPosition]; // 当前子项名称 String currentChild = text; // 按需求使用即可,示例弹吐司 String showContent = String.format("一级父级:%s\n二级父级:%s\n当前子项:%s", firstParent, secondParent, currentChild); Common.showToast(context, showContent, Toast.LENGTH_LONG); }); return convertView; }
内容的提问来源于stack exchange,提问作者Moeez
相关产品推荐
相关产品推荐

