用于android listview中类别的SectionIndexer

时间:2012-10-08 19:42:34

标签: android

我想显示listview的类别,如水果,蔬菜,其他等。

水果

- Apple

- 芒果

- 葡萄

蔬菜

- 洋葱

- 番茄

其他

- 腰带


使用CursorLoader的光标数据,

1 Apple Fruit

2芒果果实

3葡萄果实

4洋葱蔬菜

5番茄蔬菜

6其他腰带


我找不到除AlphabetIndexer之外的任何解决方案,但它没有满足我的要求。 任何人都知道如何做到这一点? [注意:我没有像isHeader这样的单独列]

1 个答案:

答案 0 :(得分:2)

SectionIndexer不会整理您加载的数据。理想情况下,您可以事先完成查询或任何支持它的集合。仅仅是SectionIndexer,允许adapterView查询支持的部分列表,以及它们的开始,结束和给定位置的位置。因此它假设您的数据已经排序。

您可以使用以下impl

制作SectionIndexer
@Override
public Object[] getSections() {
    return new CharSequence[] {"Fruit", "Vegetable", "Other"};
}

@Override
public int getSectionForPosition(int position) {
   String text = getItem(position);
   if (text.contains("Fruit") {
      return 0;
   } else if (text.contains("Vegetable") {
      return 1;
   } else {
      return 2;
   }
}

@Override
public int getPositionForSection(int section) {
   String sectionName = (String) getSections()[section];
   for (int i=0,length=getCount(); i < length; i++) {
     if (((String)getItem(i)).contains(sectionName)) {
          return i;
     }
   }
   return getCount();
}

仅供参考,这将是超级慢,因此我建议您在加载更多数据时创建索引结构,这些数据会缓存并预取这些方法请求的大部分信息。