android - SectionIndexer - 与 ArrayAdapter 和 CustomObject 一起使用?

标签 android arraylist android-listview android-arrayadapter

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

但是,如果您的 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()”的东西?

最佳答案

Where he is passing one ArrayList, I have to pass in three, but to make that happen, had to wrap in a custom object class. One of the ArrayLists that I want to sort is one of three fields in the class called "name".

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

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);
    }
}
// ...

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

Collections.sort(mData);

你的Items在哪里类必须实现Comparable<Items>接口(interface):

    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);
        }

    }

关于android - SectionIndexer - 与 ArrayAdapter 和 CustomObject 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641267/

相关文章:

java - 访问多维 ArrayList 值

java - 如果添加null,ArrayList会动态增长吗?

android - 如何在获取数据后使用 ArrayAdapter 重置 ListView

java - 带键的 Gson 字符串

android - 在android中截断小数点后的值

java - 使用子对象列表更新主对象列表

android - 如何取消 Android ListView 项目在 ListView 的 setOnItemClickListener 中被激活/突出显示?

android - 向 ArrayAdapter/ListView 添加不同的元素

java - 为我的游戏添加生命

android - 来回移动球