ListView未正确展示对应星期的Appointment模型数据问题求助
问题分析与解决方案
你遇到的核心问题很明确:更新了数据源mAppointmentList,但没有通知ListView的适配器刷新视图。当切换到周日时,你已经替换了列表内容,但ListView的适配器没有感知到数据变化,仍在使用之前的视图缓存,所以只显示了旧数据的前两条,而非你新增的周日专属时段。
解决方法
只需要在更新完mAppointmentList后,调用适配器的notifyDataSetChanged()方法,强制ListView重新渲染最新数据即可。
修改后的完整代码
HorizontalCalendar horizontalCalendar = new HorizontalCalendar.Builder(this, R.id.calendarView) .startDate(startDate.getTime()) .endDate(endDate.getTime()) .build(); horizontalCalendar.setCalendarListener(new HorizontalCalendarListener() { @Override public void onDateSelected(Date date, int position) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy", Locale.ENGLISH); SimpleDateFormat dayFormat = new SimpleDateFormat("EEE", Locale.ENGLISH); mDate = date; currentDate = dateFormat.format(date); String day = dayFormat.format(date); if (day.equals("Sun")){ mAppointmentList.clear(); mAppointmentList.add(new Appointment("1:00PM", "4:00PM" ,"Book")); mAppointmentList.add(new Appointment("4:00PM", "7:00PM" ,"Book")); } else { mAppointmentList.clear(); mAppointmentList.add(new Appointment("8:00AM", "11:00AM","Book")); mAppointmentList.add(new Appointment("11:00AM", "2:00PM" ,"Book")); mAppointmentList.add(new Appointment("2:00PM", "5:00PM" ,"Book")); mAppointmentList.add(new Appointment("5:00PM", "8:00PM" ,"Book")); } // 关键:通知适配器数据已更新,ListView将重新加载最新内容 yourListViewAdapter.notifyDataSetChanged(); } @Override public void onCalendarScroll(HorizontalCalendarView calendarView, int dx, int dy) { } @Override public boolean onDateLongClicked(Date date, int position) { return true; } });
额外注意事项
- 请将代码中的
yourListViewAdapter替换为你实际使用的ListView适配器对象的变量名 - 确保你的适配器是基于
mAppointmentList这个数据源构建的,否则调用notifyDataSetChanged()也不会生效
内容的提问来源于stack exchange,提问作者Raynold
相关产品推荐
相关产品推荐

