gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:37:37 25 4
gpt4 key购买 nike

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

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

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

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 的地方,我必须传递三个,但要做到这一点,必须包装在一个自定义对象类中。我要排序的 ArrayLists 之一是名为“名称”的类中的三个字段之一。明明是字符串。

我想根据该名称字段使用 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/

25 4 0