ListView通过适配器得到ArrayList或者数组作为数据源,我们可以对ListView的数据源按照某项进行排序。
(1)对文本内容进行排序。
Collections.sort(mArrayList, new Comparator<Map<String, Object>>() { @Override public int compare(Map<String, Object> object1, Map<String, Object> object2) { int i = object2.get("LEVEL").toString().compareTo(object1.get("LEVEL").toString()); if (i == 0) { object1.get("TITLE").toString().compareTo(object2.get("TITLE").toString()); } return i; } });
对String使用compareTo方法。
(2)对数据行数据进行排序:
Collections.sort(list, new Comparator<HashMap<String, String>>() { @Override public int compare(HashMap<String, String> map1, HashMap<String, String> map2){ int i = 0; if(Integer.parseInt(map1.get("food_day")) > Integer.parseInt(map2.get("food_day").toString())){ i = -1; } else if(Integer.parseInt(map1.get("food_day")) == Integer.parseInt(map2.get("food_day").toString())){ i = 0; } else{ i = 1; } return i; }});
直接对int型数据进行比较大小。
本文介绍如何使用Java对Android应用中的ListView组件数据进行排序。通过示例展示了两种排序方式:一种是对文本内容进行排序,另一种是对数据行数据进行排序。前者使用了String的compareTo方法,后者则是对整数类型进行了大小比较。
194

被折叠的 条评论
为什么被折叠?



