Sorting Custom Listview Items Using Spinner Android

本小妞迷上赌 提交于 2019-12-06 15:45:23

Below is the sample code, you can have a look and implement the same to your code..

public static void main(String[] args) {

    List<Item> items = new ArrayList<>();
    // constructor Item(name, Id, weight)
    items.add(new Item("Nelson", 1, 10.3));
    items.add(new Item("Fisk", 2, 12.03));
    items.add(new Item("Speedy", 3, 19.3));
    items.add(new Item("Donna", 4, 12.3));
    items.add(new Item("Matt", 5, 16.3));
    items.add(new Item("Oliver", 6, 1.3));
    items.add(new Item("Deadstroke", 5, 1.3));

    Collections.sort(items, new MyComparator(MyComparator.NAME));

    for (Item item : items) {
        System.out.println("Items   " + item.getName() + " \t" + item.getWeight());
    }
}

static class MyComparator implements Comparator<Item> {
    static final int NAME = 0, WEIGHT = 1, DATE = 2;
    int type;

    public MyComparator(int type) {
        this.type = type;
    }

    @Override
    public int compare(Item o1, Item o2) {

        if (type == NAME) {
            return o1.getName().compareTo(o2.getName());
        } else if (type == WEIGHT) {
            if (o1.getWeight() > o2.getWeight())
                return 1;
            else if (o1.getWeight() == o2.getWeight())
                return 0;
            else
                return -1;
        } else if (type == DATE) {
            // now convert your date object/string to milliseconds and apply
            // number logic (above)
        }
        return 0;
    }
}

and how you need to call in Spinner,

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedItem = parent.getItemAtPosition(position).toString();

    if (selectedItem.equals("Sort by exercise name")) {
        // Collections.sort(items, new MyComparator(MyComparator.NAME));
        //replace with your code/array list
    } else if (selectedItem.equals("Sort by date")) {
        // Collections.sort(items, new MyComparator(MyComparator.DATE));
    } else if (selectedItem.equals("Sort by number of repetitions")) {
        // Collections.sort(items, new MyComparator(MyComparator.REPTS));
    } else if (selectedItem.equals("Sort by weight")) {
        // Collections.sort(items, new MyComparator(MyComparator.WEIGHT));
    }
    adapter.notifyDataSetChanged();
    exListAdapter.notifyDataSetChanged();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!