【问题标题】:SectionIndexer - Using with ArrayAdapter and CustomObject?SectionIndexer - 与 ArrayAdapter 和 CustomObject 一起使用?
【发布时间】:2012-07-25 00:52:34
【问题描述】:

我在这里关注了一个很棒的编码示例:This SO question。它是关于实现一个 SectionIndexer 接口到一个数组适配器。

但是,如果您的 ArrayAdapter 传递的是 ArrayList 而不是 ArrayList,您将如何做同样的事情?

例如,这是我的代码与他的代码不同的地方。他有:

class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer {
private HashMap<String, Integer> alphaIndexer;
private String[] sections;

public AlphabeticalAdapter(Context c, int resource, List<String> data) {

    alphaIndexer = new HashMap<String, Integer>();
    for (int i = 0; i < data.size(); i++) {
        String s = data.get(i).substring(0, 1).toUpperCase();
        alphaIndexer.put(s, i);
    }

    // other stuff

 }

我在调整 for 循环以适应我的情况时遇到问题。我不能像他那样测量尺寸。在他有上述内容的地方,我的适配器开始了。

 public class CustomAdapter extends ArrayAdapter<Items> implements
    SectionIndexer {

     public ItemAdapter(Context context, Items[] objects) {

他传递一个 ArrayList,我必须传递三个,但要做到这一点,必须包装在一个自定义对象类中。我要排序的 ArrayList 之一是名为“name”的类中的三个字段之一。显然是一个字符串。

我想使用基于该名称字段的 SectionIndex 按字母顺序滚动浏览。如何更改其他问题中的示例代码以在这种情况下工作?

他有“data.size()”的地方,我需要像“name.size()”这样的东西——我想?

【问题讨论】:

    标签: android arraylist android-listview android-arrayadapter


    【解决方案1】:

    他在传递一个 ArrayList 的地方,我必须传递三个,但是 要做到这一点,必须包装在自定义对象类中。中的一个 我要排序的 ArrayLists 是类中的三个字段之一 称为“名称”。

    您没有三个ArrayLists,您有一个自定义对象的ArrayList,这些自定义对象是从三个ArrayLists 构建的(因此大小是您传递给适配器的List 的大小)。从这个角度来看,您的代码中唯一的变化是使用来自该自定义对象 Itemsname 来构建这些部分:

    for (int i = 0; i < data.size(); i++) {
        String s = data.get(i).name.substring(0, 1).toUpperCase();
        if (!alphaIndexer.containsKey(s)) {
            alphaIndexer.put(s, i);
        }
    }
    // ...
    

    没有其他变化。此外,您可能需要使用以下方法对传递给适配器的Items 中的List 进行排序:

    Collections.sort(mData);
    

    您的Items 类必须实现Comparable&lt;Items&gt; 接口:

        class Items implements Comparable<Items> {
            String name;
            // ... rest of the code
    
            @Override
            public int compareTo(Items another) {   
                // I assume that you want to sort the data after the name field of the Items class
                return name.compareToIgnoreCase(another.name);
            }
    
        }
    

    【讨论】:

    • 嘿,谢谢!我编辑了我的代码,显示了我应该包含的另一部分。我添加了我的适配器的构造函数。我实际上是在传递一个对象数组,而不是 ArrayLists,我相信它会再次更改 for 循环?
    • @KickingLettuce 唯一的变化是获取数据大小的语法,而不是data.size(),您将使用data.length,因为您使用的是数组。
    • 再次感谢。我确实在 Eclipse 的帮助下解决了这个问题。但是,它没有给我任何建议:'data.get(i).name.substring(0, 1)' 这是我得到的唯一错误。我认为它会是 data[i].name.substring(0,1) 但我认为它也有问题。
    • @KickingLettuce 是的,我忘记了。它应该是(只是看看)Items it = data[i]; String name = it.name; String section = name.substring(0, 1).toUpperCase();// ...。你有任何错误吗?
    • 今晚晚些时候我会试试这个,然后回复你。谢谢!在我看来它确实很坚固。一旦我得到这个工作,我会标记正确,现在,我正在为所有内容 +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多