Java 在android中对listview进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19705004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:33:00  来源:igfitidea点击:

sorting listview in android

javaandroidlistviewsorting

提问by Mohsen fallahi

i am using this code to sort my list view in alphabetic order but it doesn't sort it a-z it sorts it z-a where is The problem?

我正在使用此代码按字母顺序对我的列表视图进行排序,但它没有对其进行排序 az 它对其进行排序 za 问题在哪里?

adapter.sort(new Comparator<String>() {
    @Override 
    public int compare(String arg1, String arg0) {
        return -arg1.compareTo(arg0);
    }
});

采纳答案by Damien R.

Maybe the character '-' between returnand arg1.compareTo(arg0);?

也许字符“-”介于return和之间arg1.compareTo(arg0);

回答by Hariharan

Remove the '-'between returnand arg1.compareTo(arg0);. That will do the trick for you..

取出'-'之间returnarg1.compareTo(arg0);。这会为你做的伎俩..

The following will sort in z-a(descending) order.

以下将按 za(降序)顺序排序。

adapter.sort(new Comparator<String>() {
    @Override 
    public int compare(String arg1, String arg0) {
        return arg0.compareTo(arg1);
    }
});

For, a-z(ascending) :

对于, az(升序) :

adapter.sort(new Comparator<String>() {
        @Override 
        public int compare(String arg1, String arg0) {
            return arg1.compareTo(arg0);
        }
    });

回答by Ahmad Dwaik 'Warlock'

Use Collections.sort(yourArrayList)and then reload yourArrayList into the adapter.

使用Collections.sort(yourArrayList)然后将 yourArrayList 重新加载到适配器中。

here is some code supports my answer

这是一些代码支持我的答案

YourAdapter.java

你的适配器.java

public class YourAdapter extends BaseAdapter
{
    protected ArrayList<String> data;
    public void addSomeData()
    {
        data.add("oranj");
        data.add("apple");
        data.add("pineapple");
    }
    public YourAdapter sortData()
    {
        Collections.sort(data);
        return this;
    }
    public int getCount()
    {
        return data.size();
    }

    public String getItem(int position)
    {
        return data.get(position);
    }

    public long getItemId(int position)
    {
        return position;
    }
}

and in your activity

在你的活动中

list.setAdapter(new YourAdapter(this)); // not sorted list
list.setAdapter(new YourAdapter(this).sortData()); // sorted list