You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android如何在onItemClick中获取绑定字段ID以实现动态绑定

Android View Binding 在onItemClick中获取触发控件的实现方案

你可以直接通过onItemClick的第一个参数parent拿到触发回调的控件实例和对应的ID,不需要额外复杂的自定义实现,两种常用实现方案如下:

方案1:直接匹配控件ID(最简便)

onItemClick回调的第一个参数parent就是你设置ArrayAdapter的目标控件(也就是你示例中的binding.idCorrectionData对应的View实例),直接通过parent.getId()和布局生成的R.id常量匹配即可:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Double selectedValue = (Double) parent.getAdapter().getItem(position);
    // 匹配触发事件的控件ID
    if (parent.getId() == R.id.idCorrectionData) {
        binding.idCorrectionData.setText(selectedValue.toString());
        // 补充idCorrectionData对应的自定义逻辑
    } else if (parent.getId() == R.id.idOtherField) {
        binding.idOtherField.setText(selectedValue.toString());
        // 补充其他控件对应的自定义逻辑
    }
}

注意:绑定类的字段名称和布局文件中定义的控件ID是一一对应的驼峰转换关系,R.id.id_correction_data对应绑定类的idCorrectionData字段,匹配R.id即可定位到对应的绑定类字段。

方案2:通过Tag绑定映射关系(适合多控件场景)

如果你的业务中有大量同类型的下拉控件需要绑定,不想写大量if else判断,可以提前给每个控件设置Tag,再通过Map建立Tag和绑定类字段的映射,后续新增控件仅需新增映射配置即可:

// 初始化阶段提前建立映射关系
Map<String, TextView> dropDownFieldMap = new HashMap<>();
dropDownFieldMap.put("idCorrectionData", binding.idCorrectionData);
dropDownFieldMap.put("idOtherField", binding.idOtherField);

// 给每个设置Adapter的控件绑定对应Tag
binding.idCorrectionData.setTag("idCorrectionData");
binding.idCorrectionData.setAdapter(arrayAdapterCorrection);
binding.idOtherField.setTag("idOtherField");
binding.idOtherField.setAdapter(arrayAdapterOther);

// onItemClick中直接通过Tag取对应控件
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Double selectedValue = (Double) parent.getAdapter().getItem(position);
    String fieldTag = (String) parent.getTag();
    TextView targetField = dropDownFieldMap.get(fieldTag);
    if (targetField != null) {
        targetField.setText(selectedValue.toString());
        // 通用逻辑处理
    }
}

内容的提问来源于stack exchange,提问作者stasieki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:09:03