Android Kotlin中如何获取RecyclerView当前与上次选中项的位置?
RecyclerView日历多日期区间选择实现方案
1. 在CalendarAdapter中维护选中状态变量
首先在Adapter类里定义核心变量,跟踪选中位置与区间:
// 上一次选中的位置 private int lastSelectedPos = -1; // 当前选中的位置 private int currentSelectedPos = -1; // 存储区间内所有选中的位置 private Set<Integer> selectedRange = new HashSet<>();
2. 实现Item点击事件与样式控制
在onBindViewHolder方法中,先根据选中状态设置Item样式,再处理点击逻辑:
@Override public void onBindViewHolder(@NonNull CalendarViewHolder holder, int position) { // 重置Item默认样式 resetDefaultStyle(holder); // 如果当前位置在选中区间内,应用选中样式 if (selectedRange.contains(position)) { applySelectedStyle(holder); } // 处理Item点击 holder.itemView.setOnClickListener(v -> { if (lastSelectedPos == -1) { // 首次选中,初始化起始位置 lastSelectedPos = position; currentSelectedPos = position; selectedRange.add(position); } else if (position == currentSelectedPos) { // 点击已选中位置,取消所有选中状态 lastSelectedPos = -1; currentSelectedPos = -1; selectedRange.clear(); } else { // 清空旧选中区间 selectedRange.clear(); // 确定区间的起始与结束位置 int start = Math.min(lastSelectedPos, position); int end = Math.max(lastSelectedPos, position); // 将区间内所有位置加入选中集合 for (int i = start; i <= end; i++) { selectedRange.add(i); } // 更新选中位置记录 lastSelectedPos = currentSelectedPos; currentSelectedPos = position; } // 刷新Adapter,更新样式 notifyDataSetChanged(); }); } // 重置Item为默认样式 private void resetDefaultStyle(CalendarViewHolder holder) { holder.dateTextView.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.calendar_default_bg)); holder.dateTextView.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.calendar_default_text)); // 按需添加其他样式重置逻辑 } // 应用选中样式 private void applySelectedStyle(CalendarViewHolder holder) { holder.dateTextView.setBackgroundColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.calendar_selected_bg)); holder.dateTextView.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), R.color.calendar_selected_text)); // 按需添加其他选中样式逻辑 }
3. 处理月份切换等边界场景
当日历切换月份时,重置选中状态避免跨月错误:
// 对外提供重置选中状态的方法 public void resetSelection() { lastSelectedPos = -1; currentSelectedPos = -1; selectedRange.clear(); notifyDataSetChanged(); }
在月份切换的逻辑中调用此方法即可。
补充说明
- 若需将选中的日期数据回传给上层页面,可在Adapter中定义回调接口,在点击事件触发时传递选中日期集合。
- 样式颜色可根据UI需求替换为对应颜色资源。
内容的提问来源于stack exchange,提问作者Euna J
相关产品推荐
相关产品推荐

