从适配器中生成的值而不是对象变量中的值中排序回收文章



从ArrayList中的值中对arrayList进行排序是没有问题的,但是我有一个直接在适配器中计算的int,我更喜欢将其保留在那里,因为它看起来像一个干净解决方案。

timeleftinminutes是我要为回收库排序的值,但我不知道如何将其进入活动(确切的计算并不那么重要):

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    int dueHour = mTaskList.get(position).getDueHour();
    int dueMinute = mTaskList.get(position).getDueMinute();
    Calendar calendar = Calendar.getInstance();
    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
    int currentMinute = calendar.get(Calendar.MINUTE);
    //correcting values to over 24 if necessary
    int mBedHourPlus24IfNecessary;
    if (mBedHour < mWakeUpHour || mBedHour == mWakeUpHour && mBedMinute < mWakeUpMinute) mBedHourPlus24IfNecessary = mBedHour + 24;
    else mBedHourPlus24IfNecessary = mBedHour;
    int mDueHourPlus24IfNecessary;
    if (dueHour < mWakeUpHour ) mDueHourPlus24IfNecessary = dueHour + 24;
    else mDueHourPlus24IfNecessary = dueHour;

    int timeLeftInMinutes;
    if (mDueHourPlus24IfNecessary > mBedHourPlus24IfNecessary || mDueHourPlus24IfNecessary == mBedHourPlus24IfNecessary && dueMinute > mBedMinute) {
        holder.mTimeLeft.setText(mContext.getResources().getString(R.string.while_sleeping));
        holder.mCardContainer.setCardBackgroundColor(ContextCompat.getColor(mContext, R.color.task_blue));
        timeLeftInMinutes = 999999999;
    } else {
        timeLeftInMinutes = (mDueHourPlus24IfNecessary * 60 + dueMinute) - (currentHour * 60 + currentMinute);
}

使用onBindViewHolder不是一个好主意,因为它仅适用于要出现在屏幕上的对象,因此您不知道所有项目的timeLeftInMinutes。/p>

一个更好的解决方案是将其添加到适配器中,该方法可以通过您的数组,计算每个项目的时间,将其保存到项目中,将适配器通知列表已准备就绪

public void updateAndSort(List<MyObject> list) {
    //Go through all your item and computer their time left.
    for (int i = 0; i < list.size(); i++) {
        //Compute the value you need to compare for each item
        list.get(i).timeLeftInMinute = timeComputed...
    }
    //Then you order your list, for example ascendant
    Collections.sort(list, new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            if (o1.timeLeftInMinute > o2.timeLeftInMinute) {
                return 1;
            } else {
                return -1;
            }
        }
    });
    //replace your mTaskList the sorted list to your adapter
    mTaskList = list;
    //notify the adapter to correctly display the times
    notifyDataSetChanged()
}

最新更新