【问题标题】:Sorting baseadpter using Comparator does not sort使用 Comparator 对 baseadpter 进行排序不会排序
【发布时间】:2025-12-01 14:15:02
【问题描述】:

我有一个自定义对象的数组列表 (ArrayList)。

每个对象都通过 getter/setter 方法保存数据。

我想将对象的数组列表添加到 baseadpter 并显示根据名为 'PackageName' 的对象属性排序的列表视图(方法 object.getProccess() 将返回一个字符串名称)。

在我的自定义对象类中,我使用这个静态方法实现了 Comparable 接口:

 // implement Comparable interface to allow sort in aplhapbetically order the adpter sent
         // to the list view

         public static Comparator <ProcessDetails> PacageNameComparator = new Comparator<ProcessDetails>(){

            @Override
            public int compare(ProcessDetails name1, ProcessDetails name2) {
                // TODO Auto-generated method stub

                String nameA = name1.getProcess();
                String nameB = name2.getProcess();

                //accesnding order


                return nameA.compareTo(nameA);
            }




         };

当我使用自定义对象的 ArrayList (ArrayList ProcessDetails) 设置适配器(baseadapter)时,我首先尝试对其进行排序:

Collections.sort(detailAllsApp, ProcessDetails.PacageNameComparator);

            myAdapter = new ListViewAdapter(detailAllsApp,
                    getApplicationContext(), TaskKillerTabActivity.myTypeface);

            // myAdapter = new ListViewAdapter(detailsApp,
            // getApplicationContext(),
            // TaskKillerTabActivity.myTypeface);
            applicationProcessList.setAdapter(myAdapter);
            myAdapter.notifyDataSetChanged();

            // allow one item selection at at time only

            applicationProcessList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

但是返回的列表从不按字母顺序排列。 任何反馈表示赞赏。

【问题讨论】:

    标签: android sorting baseadapter


    【解决方案1】:

    如果您返回一个对象与其自身的比较,比较器就不会真正起作用。应该是:

    return nameA.compareTo(nameB);
    

    【讨论】:

    • 第二双眼睛需要欢呼……“如果我有一个小时来解决一个问题,我会花 55 分钟思考问题和 5 分钟思考解决方案。”