gpt4 book ai didi

android - 从适配器中生成的值而不是对象变量对 RecyclerView 进行排序?

转载 作者:行者123 更新时间:2023-11-29 19:08:41 25 4
gpt4 key购买 nike

根据 ArrayList 中的值对 ArrayList 进行排序没有问题,但我有一个直接在 Adapter 中计算的 int,我更愿意将它保留在那里,因为它看起来是一个干净的解决方案。

timeLeftinMinutes 是我要为 RecyclerView 排序的值,但我不知道如何将它放入 Activity(具体计算不是那么重要):

@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 对于所有项目。

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

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()

}

关于android - 从适配器中生成的值而不是对象变量对 RecyclerView 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com