我在这里遵循一个很棒的编码示例:This SO question 。它是关于实现数组适配器的SectionIndexer 接口(interface)。
但是,如果您的 ArrayAdapter 传递的是 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/