【问题标题】:How to apply sorting on list of item in android如何在android中的项目列表上应用排序
【发布时间】:2012-01-01 21:14:32
【问题描述】:

我正在开发一个 Android 项目。我有一个项目列表,一行有三列。 现在我需要根据这些列对列表进行排序。 列标题为:number, name, summary

现在,如果我单击数字,则列表应按数字排序,如果单击名称,则列表应按名称排序。

现在我没有得到应该在 Android 中用于该标题的布局或事件。

请给我建议。

【问题讨论】:

    标签: android list sorting android-layout android-listview


    【解决方案1】:

    编辑:

    你必须阅读这个类似的问题,你才能对你的数据进行排序:

    How to sort an ArrayList using multiple sorting criteria?

    对数据进行排序后,您只需在适配器上调用 notifyDataSetChanged:

    yourAdapter.notifyDataSetChanged();
    

    有关排序的更多信息: http://en.allexperts.com/q/Java-1046/Sort-2-attributes-collection.htm

    首先,为每个类创建一个 Comparator 类 您可能需要的 Employee 类的不同方面。 例如:

        public class EmployeeAgeComparator
           implements Comparator 
       {
               public int compare(Object o1, Object o2) {
                    int age1 = ((Employee)o1).getAge();
                    int age2 = ((Employee)o2).getAge();
                    if (age1 < age2) return -1;
                    if (age2 < age1) return  1;
                    return 0;
               }
         }
    

    一旦您获得了 EmployeeIdComparator、EmployeeNameComparator 和其他所有内容,然后使用以下代码:

           Comparator mc;
           mc = new EmployeeIdComparator();
           Collections.sort(list, mc);
    

    【讨论】:

    • 不知道你为什么从某人那里得到-1。您的回答已经足够好了:只需对基础列表进行排序并通知观察者有关更改。
    • @Profete162:问题不在于如何对数据进行排序。问题是如何在android应用程序中实现。就像在开发网页时,我们可以让表头可点击。但是在android中该怎么做。问题是布局。
    • 请提出一个正确的问题...想帮忙,但我无法理解您想要什么!您想解释如何在按钮点击上添加此代码吗?
    【解决方案2】:

    你可以在你的列表适配器中使用比较器

    public class CustomerByNameComparator implements Comparator<Customer>
    { 
        public int compare(Customer o1, Customer o2) {
            return o1.getName().compareToIgnoreCase( o2.getName() );
        }
    }
    

    希望对你有所帮助......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      相关资源
      最近更新 更多