2012-10-22 60 views
0

我想根据应用程序中的某些值对Listview进行排序,但我不知道如何对其进行编码。我研究并发现人们正在使用比较器和集合来对数组列表进行排序。基本上,我想根据某些状态进行排序,如接受或拒绝。该值存储在TAG_ACCEPT_REJECT中,并显示在R.id.applicantStatus中。使用SimpleAdapter进行排序

下面是我的代码:

adapter = new SimpleAdapter(
       ApplicantJobStatusActivity.this, 
       applicantsList, 
       R.layout.list_applicant_status, 
       new String[] { TAG_UID, TAG_NAME, 
           TAG_ACCEPT_REJECT, 
           TAG_ACCEPT_REJECT_DATETIME }, 
       new int[] { R.id.applicantUid, 
          R.id.applicantName, 
          R.id.applicantStatus, 
          R.id.accept_reject_datetime }); 
setListAdapter(adapter); 

我想知道如何以及在何处使用比较器和采集重新安排我的ListView放置分类代码。

回答

3

在将它传递给适配器之前,应该对列表applicantsList进行排序。然后您可以使用Collections.sort方法。类似的东西:

Collections.sort(applicantsList, new Comparator<T extends Map<String, ?>> { 
    public int compare(T map1, T map2) { 
    if (!map1.has(TAG_ACCEPT_REJECT)) return -1; 
    if (!map2.has(TAG_ACCEPT_REJECT)) return 1; 

    // Assumes the objects you store in the map are comparables 
    return map1.get(TAG_ACCEPT_REJECT).compareTo(map2.get(TAG_ACCEPT_REJECT)); 
    } 
}); 
+1

使用此功能可以用来初始化SimpleArrayAdapter数组进行排序,你就可以走了。此外,你可能想重新写你的ArrayAdapter实现自动排序每个dataSetChanged()或getView() – Shark

+0

我在哪里把这个Collections.sort()代码?在onCreate方法里面? –

+0

从我的回答:“您应该在将您的列表申请人列表传递给您的适配器之前对其进行排序。”所以在'adapter = new SimpleAdapter('看起来好像是一个好地方)之前 –

1

-使用Arrays.sort()以前分配ArrayAdapter

-或者您可以使用Collections.sort(Collection c)Comparable接口,

-或者Collections.sort(Collection c, Comparator cp)Comparator Interface, with Colletions like的ArrayList before assigning it to the Adapter`。

/////////////////////////编辑部分////////////////// ////////

请参阅下面的链接,其中包含所有使用各种技术排序Array,ArrayList等的示例

http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

+0

Im new to android。你能告诉我一些例子吗? –

+0

@ SarahPhil看到我编辑的答案.... –

+0

okok谢谢!如果我还有其他问题,我再次问你。 –