【问题标题】:Accounting for ListView sort while ignoring leading "The" in Android考虑 ListView 排序,同时忽略 Android 中的前导“The”
【发布时间】:2012-08-30 19:45:24
【问题描述】:

我有一个由三 (3) 个 ArrayList 填充的 ListView

itemsratingscomments

但是,我需要通过忽略前导“the”来对项目进行排序。我已经通过使用Collections.sort 重新排列items ArrayList 来完成此操作(请参见下面的代码),但这是问题所在:cmets 和评级没有重新排列,因此它在ListView 中出现乱序。

例如,如果列表是:

  1. 汽车 3 4
  2. 人5 3
  3. 动物 7 4

items 排序后我得到:

  1. 动物 3 4
  2. 汽车 5 3
  3. 人 7 4

所以items 按我的意愿排列,但关联的commentsratings 没有排序。我不确定如何做到这一点以及将其放置在哪里。我认为在 ArrayAdapter 中?

这是我更改items 列表的代码:

        Comparator<String> ignoreLeadingThe = new Comparator<String>() {
            public int compare(String a, String b) {
                a = a.replaceAll("(?i)^the\\s+", "");
                b = b.replaceAll("(?i)^the\\s+", "");
                return a.compareToIgnoreCase(b);
            }
        };

        Collections.sort(items, ignoreLeadingThe);

这是问题吗?我可以在哪里以及如何根据项目列表的位置对评级和 cmets 列表进行排序?

编辑:

这是我在ArrayAdapter 中的getView 代码:

    ItemObject io = getItem(position);
    String name = io.name;
    String total = io.total;
    String rating = io.ratings;
    String comment = io.comments;

    holder.t1.setText(name);
    holder.t2.setText(total);
    holder.t3.setText(comment);
    holder.t4.setText(rating);

注意:还有一个名为total 的第四个ArrayList 我在上面的例子中没有提到。

【问题讨论】:

    标签: android sorting android-listview android-arrayadapter


    【解决方案1】:

    您应该考虑创建一个类来将您的项目包装在 ArrayList 中,如下所示:

    class MyItem {
        String item;
        int ratings;
        int comments;
    }
    

    然后用这些对象的 ArrayList 代替:

    List<MyItem> myList = new ArrayList<MyItem>();
    

    然后在您的比较器中,像您正在做的那样做,但要针对MyItem.item 而不是仅ab 进行测试。像这样的:

    Comparator<MyItem> ignoreLeadingThe = new Comparator<MyItem>() {
        public int compare(MyItem a, MyItem b) {
            a.item = a.item.replaceAll("(?i(^the\\s+", "");
            b.item = b.item.replaceAll("(?i(^the\\s+", "");
            return a.item.compareToIgnoreCase(b.item);
        }
    };
    
    Collections.sort(myList, ignoreLeadingThe);
    

    【讨论】:

    • 太棒了!我已经有一个我正在使用的类。我更新了我的问题,向您展示我如何从 getView 方法中的类/对象输出。这是我会在上面使用您的代码的地方吗?还是在调用适配器之前在主 ListActivity 中执行此操作?
    • 是的!您可以只使用 ItemObject 类而不是我用作示例的 MyItem 类。
    • 好的,关于实施的另一个快速问题:我不确定在Collections.sort 中添加什么。它必须是一个列表,对吧?我们真的在分类“项目”吗?我们现在不是在对 ItemObject 进行排序吗?
    • 您正在对ListItemObjects 进行排序。 items 应该是 ArrayList&lt;ItemObject&gt;。我刚刚从您的描述中复制了items,但在我的示例中,它应该是myList。我将进行编辑以使其更清晰。
    • 好吧,我就是这么想的。这在我的代码中正常工作,没有错误。虽然还没有排序(基于修剪“the”)。我实际上是在我的适配器设置之前而不是在我的适配器中尝试这种排序。 (希望这是对的?)我会标记你是正确的,因为我认为你让我走上了正确的道路!
    猜你喜欢
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多