排序
Android 文件浏览器中涉及到文件按照文件名称、文件大小、修改时间 ,记录其排序算法如下,方便日后简单修改参考使用:
/** * sort file * * @param fileList // file list * @param sortMethod 「名称、大小、时间」 * @param MA 「Context」 * @return List<File> */public static List<File> sortFile(List<File> fileList, final String sortMethod, final CommonActivity MA) { Collections.sort(fileList, new Comparator<File>() { @Override public int compare(File object1, File object2) { return compareFile(object1, object2, sortMethod, MA); } }); return fileList; }/** * A local file, mount the directory to sort the files to achieve CNcomment: * 本地文件,挂载目录文件排序实现 * * @param object1 * @param object2 * @param sortMethod * @param MA * @return */public static int compareFile(File object1, File object2, String sortMethod, CommonActivity MA) { mx = MA; if (sortMethod.equals(mx.getResources().getString(R.string.file_name))) { return compareByName(object1, object2); } else if (sortMethod.equals(mx.getResources().getString( R.string.file_size))) { int len = compareBySize(object1.length(), object2.length()); // the same size ,sort by name if (len == 0) { return compareByName(object1, object2); } else { return compareBySize(object1.length(), object2.length()); } } else if (sortMethod.equals(mx.getResources().getString( R.string.update_time))) { int len = compareByDate(object1.lastModified(), object2.lastModified()); // the same data ,sort by name if (len == 0) { return compareByName(object1, object2); } else { return compareByDate(object1.lastModified(), object2.lastModified()); } } return 0; }/** * sort according to file name * * @param object1 * @param object2 * @return */private static int compareByName(File object1, File object2) { String objectName1 = object1.getName().toLowerCase(); String objectName2 = object2.getName().toLowerCase(); int result = objectName1.compareTo(objectName2); if (result == 0) { return 0; } else if (result < 0) { return -1; } else { return 1; } }/** * sort according to file size * * @param object1 * @param object2 * @return */private static int compareBySize(long object1, long object2) { long diff = object1 - object2; if (diff > 0) { return 1; } else if (diff == 0) { return 0; } else { return -1; } }/** * file sorted by date modified * * @param object1 * @param object2 * @return */public static int compareByDate(long object1, long object2) { long diff = object1 - object2; if (diff > 0) { return 1; } else if (diff == 0) { return 0; } else { return -1; } }
作者:DB_Liu
链接:https://www.jianshu.com/p/3eebe555d26a
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦