我习惯于每次需要更新RecycleView中的闹钟时都创建一个新的Adapter和一个新的RecycleView。不幸的是,这只是一种非常昂贵的“解决方案”。我在网上看到可以使用DiffUtil,但我不确定如何实现它。我创建了一个DiffUtil类:
public class AlarmDiffCallBack extends DiffUtil.Callback{
private final ArrayList<SingleAlarm> oldList;
private final ArrayList<SingleAlarm> newList;
public AlarmDiffCallBack( ArrayList<SingleAlarm> oldList, ArrayList<SingleAlarm> newList) {
this.oldList = oldList;
this.newList = newList;
}
@Override
public int getOldListSize() {
return oldList.size();
}
@Override
public int getNewListSize() {
return newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).getAlarmIndex() == newList.get(newItemPosition).getAlarmIndex();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).getAlarmIndex() == newList.get(newItemPosition).getAlarmIndex();
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
// Implement method if you're going to use ItemAnimator
return super.getChangePayload(oldItemPosition, newItemPosition);
}
这是我想要更新 RecyclerView 的其中一个位置(使用 DiffUtil 替换 "creatAdapter"):
public void add_alarm(final Context context) {
//creating a new alarm and set the relevant varible to the addAlarm function
button_add_alarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//the calndar is without the right day, the day is added in the handler(int the loop)
Calendar calendarForAlarm = timePickerToCalendar(alarmTimePicker);
alarmsList = alarmHandler.add_alarm(context, checkBoxes, alarmMessage, alarmsList, alarm_manager, calendarForAlarm, repeatAlarm);
alarmsList=alarmHandler.sortAlarms(alarmsList);
creatAdapt();
}
});
}
我只是不知道如何使用这个类来更新我的Adapter。我对安卓和编程一般都很新,希望这句引言没问题。谢谢!