在忽略前导“的情况下计算ListView排序;";在Android中
我有一个在忽略前导“的情况下计算ListView排序;";在Android中,android,sorting,android-listview,android-arrayadapter,Android,Sorting,Android Listview,Android Arrayadapter,我有一个列表视图,由三(3)个数组列表填充: 项目,评分和评论 但是,我需要通过忽略前导的“the”来对项目进行排序。我已经通过使用Collections.sort(请参见下面的代码)重新排列项数组列表,完成了这一点,但问题在于:注释和评级没有重新排列,因此在列表视图中出现顺序混乱 例如,如果列表为: 汽车3 4 人5 3 动物7 4 在项目之后我得到的排序: 动物3 4 汽车5 3 人民7 4 因此,项目按照我的意愿排列,但是相关的评论和评分没有排序。我不知道如何做到这一点,以及把它放在哪里。
列表视图
,由三(3)个数组列表
填充:
项目
,评分
和评论
但是,我需要通过忽略前导的“the”来对项目进行排序。我已经通过使用Collections.sort
(请参见下面的代码)重新排列项
数组列表
,完成了这一点,但问题在于:注释和评级没有重新排列,因此在列表视图
中出现顺序混乱
例如,如果列表为:
项目之后
我得到的排序:
项目
按照我的意愿排列,但是相关的评论
和评分
没有排序。我不知道如何做到这一点,以及把它放在哪里。我想在ArrayaAdapter
以下是我更改项目
列表的代码:
Comparator<String> ignoreLeadingThe = new Comparator<String>() {
public int compare(String a, String b) {
a = a.replaceAll("(?i)^the\\s+", "");
b = b.replaceAll("(?i)^the\\s+", "");
return a.compareToIgnoreCase(b);
}
};
Collections.sort(items, ignoreLeadingThe);
注意:在上面的示例中,我没有提到第四个
ArrayList
名为total
。您应该考虑创建一个类来包装ArrayList中的项目,如下所示:
class MyItem {
String item;
int ratings;
int comments;
}
Comparator<MyItem> ignoreLeadingThe = new Comparator<MyItem>() {
public int compare(MyItem a, MyItem b) {
a.item = a.item.replaceAll("(?i(^the\\s+", "");
b.item = b.item.replaceAll("(?i(^the\\s+", "");
return a.item.compareToIgnoreCase(b.item);
}
};
Collections.sort(myList, ignoreLeadingThe);
然后创建这些对象的ArrayList:
List<MyItem> myList = new ArrayList<MyItem>();
太棒了!我已经有了一个我正在使用的类。我更新了我的问题,向您展示了如何在getView方法中从类/对象输出。这是我使用上面代码的地方吗?还是在调用适配器之前在主ListActivity中执行此操作?是的!您可以使用您的
ItemObject
类,而不是我用作示例的MyItem
类。好的,还有一个关于实现的快速问题:我不确定在集合中放置什么。排序
。它必须是一个列表,对吗?我们真的在分类“项目”吗?我们现在不是在对ItemObject进行排序吗?您正在对ItemObject
s的列表进行排序<代码>项
应为数组列表
。我刚刚从您的描述中复制了项
,但从我的示例来看,它应该是我的列表
。我会编辑使它更清晰。好的,我就是这么想的。在我的代码中工作,没有错误。。尽管还没有任何东西被分类(基于修剪“the”的)。我实际上是在设置适配器之前而不是在适配器中尝试这种排序。(希望这是对的?)我会为你做正确的标记,因为我认为你让我走上了正确的道路!
Comparator<MyItem> ignoreLeadingThe = new Comparator<MyItem>() {
public int compare(MyItem a, MyItem b) {
a.item = a.item.replaceAll("(?i(^the\\s+", "");
b.item = b.item.replaceAll("(?i(^the\\s+", "");
return a.item.compareToIgnoreCase(b.item);
}
};
Collections.sort(myList, ignoreLeadingThe);