使用Collection.sort排序listView项时出错

时间:2014-03-25 15:02:22

标签: android listview

您好我想按字母顺序对listView项目进行排序。我知道SOF关于这个问题还有其他问题,但没有一个答案适合我。

public class myList extends Activity{

// Tab Host
TabHost th;
LinearLayout tab1, tab2;

//List
ListView myListView;
String string_list[] = { "String1", "String2", "String3", "String", "String5", "String6"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    // XML File
    setContentView(R.layout.main_list);

    // TabHost
    initializeTab();

    // ListView
    myListView = (ListView) findViewById (R.id.listView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,string_list);
    myListView.setAdapter(adapter); 

            myListView.setItemsCanFocus(false);
    myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    Collections.sort(myListView, String.CASE_INSENSITIVE_ORDER);
}

我的Collections.sort声明中出现了错误:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (ListView, Comparator<String>)

3 个答案:

答案 0 :(得分:1)

更改

Collections.sort(myListView, String.CASE_INSENSITIVE_ORDER);

Arrays.sort(string_list, String.CASE_INSENSITIVE_ORDER);

然后

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,string_list);
    myListView.setAdapter(adapter); 

答案 1 :(得分:1)

正确的课程如下:

public class myList extends Activity {

    // Tab Host
    TabHost th;
    LinearLayout tab1, tab2;

    //List
    ListView myListView;
    String[] string_list = { "String1", "String2", "String3", "String", "String5", "String6"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        // XML File
        setContentView(R.layout.main_list);

        // TabHost
        initializeTab();

        // ListView
        myListView = (ListView) findViewById (R.id.listView1);
        Arrays.sort(string_list, String.CASE_INSENSITIVE_ORDER);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,string_list);
        myListView.setAdapter(adapter);

        myListView.setItemsCanFocus(false);
        myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }
}

请注意,Array!= Collection

答案 2 :(得分:0)

最快的解决方案是使用适配器的sort方法:

adapter.sort(String.CASE_INSENSITIVE_ORDER);