让我们假设我有一个网络请求的膳食清单和实现使用一个回收视图,现在,如果我想排序/移动特定的项目在顶部..!
餐:意大利意大利面食类型:意大利面食价格:20美元
餐:热狗必胜客型:比萨价格:10美元
餐:汉堡包型:快餐价格:30美元
套餐:类型:午餐价格:18美元
餐: Mac & Cheese 类型:午餐价格:17美元
餐: CheeseBurger 类:快餐价格:8美元
因此,例如,我想要的是,对于每一个项目谁有一个类型的fast food和pizza显示在列表的顶部,然后其余的.!?
我在哪里执行这个排序逻辑,它是在适配器内还是在回收视图的活动中?对于像moveToTop()这样的函数是否有一个现有的方法可以这样使用:
for(Meals item: dataList){
if (item.getType.equals("fast food") || item.getType.equals("pizza")){
item.moveToTop();
}
}有可能吗?
更新2
我想出了一种方法,在这种情况下,我为回收视图找到了一个特殊的接口参数SortedListAdapterCallback。
if (homeData.size() > 0) {
Collections.sort(homeData, Collections.reverseOrder(new SortedListAdapterCallback<HomeItemModel>(adapter) {
@Override
public int compare(HomeItemModel o1, HomeItemModel o2) {
int weight1;
int weight2;
if(item1.getType.equals("fast food") || item1.getType.equals("pizza")){
weight1 = 1;
}else{
weight1 = 0;
}
if(item2.getType.equals("fast food") || item2.getType.equals("pizza")){
weight2 = 1;
}else{
weight2 = 0;
}
if (weight1 == weight2)
return 0;
else if (weight1 > weight2)
return 1;
else
return -1;
}
@Override
public boolean areContentsTheSame(HomeItemModel oldItem, HomeItemModel newItem) {
return false;
}
@Override
public boolean areItemsTheSame(HomeItemModel item1, HomeItemModel item2) {
return false;
}
}));
}这里唯一的问题是上面的订单..!他们表现得像这样:
,我要他们出示命令..。像这样:
这能做吗..?
发布于 2017-09-13 13:05:46
在POJO类餐内创建一个比较器
public static class CustomComparator implements Comparator<Meals> {
public int compare(Meals item1, Meals item2) {
int weight1;
int weight2;
if(item1.getType.equals("fast food") || item1.getType.equals("pizza")){
weight1 = 1;
}else{
weight1 = 0;
}
if(item2.getType.equals("fast food") || item2.getType.equals("pizza")){
weight2 = 1;
}else{
weight2 = 0;
}
if (weight1 == weight2)
return 0;
else if (weight1 > weight2)
return 1;
else
return -1;
}
}在设置适配器之前,调用这一行,然后将数据列表传递到adapter构造函数中。
Collections.sort(yourDataLIst, Collections.reverseOrder(new Meals.CustomComparator()));编辑如果你想要所有的快餐,然后是披萨,然后所有的列表,然后调整你的排序逻辑,如下所示
if(item1.getType.equals("fast food")){
weight1 = 2;
}else if (item1.getType.equals("pizza")){
weight1 = 1;
} else {
weight1 = 0;
}
if(item2.getType.equals("fast food")){
weight2 = 2;
}else if (item2.getType.equals("pizza")){
weight2 = 1;
} else{
weight2 = 0;
}发布于 2017-09-13 13:03:57
在moveToTop() Arraylist中没有像这样的简单方法。但是你可以手动转换数据。
你可以这样做:
for(Meals item: dataList){
if (item.getType.equals("fast food") || item.getType.equals("pizza")){
int index = dataList.indexOf(item);
dataList.remove(index);
dataList.add(0, item);
adapter.notifyDataSetChanged()
}
}希望它有帮助:)
https://stackoverflow.com/questions/46198160
复制相似问题