参数里面的isAscend 用来决定是升序排列 还是降序排列:
补充上三个comparator:
/***
* 按最后修改时间排序
* @param list
* @param isAscend
*/
public static void sortListByTime(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByTime comparator = new ComparatorByTime(isAscend);
if (!list.isEmpty()) {
Log.e("sortListByTime()", "");
synchronized (list) {
Collections.sort(list, comparator);
}
}
}
/**
* 按文件大小排序
* @param list
*/
public static void sortListBySize(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorBySize comparator = new ComparatorBySize(isAscend);
if (!list.isEmpty()) {
Log.e("sortListBySize()", "");
synchronized (list) {
Collections.sort(list, comparator);
}
}
}
/**
* 按文件名称排序
* @param list
*/
public static void sortListByName(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByName comparator = new ComparatorByName(isAscend);
if (!list.isEmpty()) {
Log.e("sortListByName()", "");
synchronized (list) {
Collections.sort(list, comparator);
}
}
}
补充上三个comparator:
public class ComparatorByName implements Comparator<FileInfo>{
boolean isAscend;
public ComparatorByName(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {
if(isAscend == true){
return Collator.getInstance(Locale.CHINESE).compare(f1.fileName, f2.fileName);
} else {
return Collator.getInstance(Locale.CHINESE).compare(f2.fileName, f1.fileName);
}
}
}
public class ComparatorBySize implements Comparator<FileInfo>{
boolean isAscend;
public ComparatorBySize(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {
long temp = new File(f2.filePath).length() - new File(f1.filePath).length();
if(isAscend == false){
if(temp > 0){
return 1;
}else if(temp == 0 ){
return 0;
}else{
return -1;
}
}else{
if(temp > 0){
return -1;
}else if(temp == 0 ){
return 0;
}else{
return 1;
}
}
}
}
public class ComparatorByTime implements Comparator<FileInfo>{
boolean isAscend;
public ComparatorByTime(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {
if(isAscend == false){
return f2.lastModifiedTime.compareTo(f1.lastModifiedTime);
} else {
return f1.lastModifiedTime.compareTo(f2.lastModifiedTime);
}
}
}