【问题标题】:Sorting list of custom objects wrt a property in android studio (API level problem)在android studio中对自定义对象的排序列表(API级别问题)
【发布时间】:2019-02-27 09:40:44
【问题描述】:

我想根据 android.xml 中的一个属性(变量类型为“long”)按降序对自定义对象列表进行排序。为此,我使用了 Collections Comparator,但我的问题是它说“Long.compare 调用需要 API 级别 19(当前最小值为 16)”有没有其他方法来处理这个问题? (代码在我的虚拟设备上运行完美,没有错误,但我希望它在 API 级别低于 19 的设备上运行)

我的排序代码是:

// Sort the news according to their last update time (show the latest on top)
    Collections.sort(news, new Comparator<NewsItem>() {
        @Override
        public int compare(NewsItem newsItem1, NewsItem newsItem2) {
            return Long.compare(newsItem2.getUpdateTime(), newsItem1.getUpdateTime());
        }
    });

我的自定义对象是具有五个属性的 NewsItem,我想将列表排序为 Long 类型的 UpdateTime 属性。

【问题讨论】:

    标签: java android list sorting comparator


    【解决方案1】:

    您可以为时间创建Long 对象并直接比较它们:

    Collections.sort(news, new Comparator<NewsItem>() {
        @Override
        public int compare(NewsItem newsItem1, NewsItem newsItem2) {
            return Long.valueOf(newsItem2.getUpdateTime()).compareTo(
                   Long.valueOf(newsItem1.getUpdateTime()));
        }
    });
    

    附带说明 - API 级别 16 已经过时,您可能需要考虑升级您的要求。

    【讨论】:

    • 建议支持多设备,将minSdkLevel保持为低,所以我选择API级别16,但我可以增加它。感谢穆雷尼克的回答。
    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2011-06-30
    相关资源
    最近更新 更多