You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android中实现Spinner列表项按价格升序排列

实现方案

你当前排序异常是默认按字符串字典序排序导致的(例如字典序下"100" < "20"),只需要在创建GenericArrayAdapter之前,对slectedSmsEntities按Sm实体的price字段做数值升序排序即可。

具体修改步骤

  1. 在setupPrice()方法中,初始化适配器的代码之前,添加列表排序逻辑:
    如果你的Sm.getPrice()返回的是数字类型(int/Integer/double/Double),直接用如下代码:
// 按price字段升序排序
Collections.sort(slectedSmsEntities, new Comparator<Sm>() {
    @Override
    public int compare(Sm o1, Sm o2) {
        // 先判空,避免空指针异常
        if (o1 == null || o1.getPrice() == null) return 1;
        if (o2 == null || o2.getPrice() == null) return -1;
        // 升序排序,要降序的话把o1和o2调换位置即可
        return Integer.compare(o1.getPrice(), o2.getPrice());
        // 如果price是浮点型就用下面这句
        // return Double.compare(o1.getPrice(), o2.getPrice());
    }
});

如果你的Sm.getPrice()返回的是字符串类型,先转成数值再比较:

Collections.sort(slectedSmsEntities, new Comparator<Sm>() {
    @Override
    public int compare(Sm o1, Sm o2) {
        if (o1 == null || o1.getPrice() == null) return 1;
        if (o2 == null || o2.getPrice() == null) return -1;
        try {
            int price1 = Integer.parseInt(o1.getPrice());
            int price2 = Integer.parseInt(o2.getPrice());
            return Integer.compare(price1, price2);
        } catch (NumberFormatException e) {
            // 转换失败的项放到列表最后
            return 1;
        }
    }
});
  1. 排序完成后再执行原来的适配器初始化逻辑即可,后续Spinner展示的列表就是按10、20、50、100的升序排列的效果。

可选优化

如果你的列表数据会动态变更,可以在更新列表后调用priceAdapter.notifyDataSetChanged()刷新展示,排序逻辑可以复用上面的代码。

内容的提问来源于stack exchange,提问作者Mahmoud Al-Haroon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:06:04