1

在我的项目中,我有扩展ArrayAdapter<String>和实现的类SectionIndexer。在实现方法时getPositionForSectiongetSectionForPosition我发现了一些奇怪的行为。

为什么节索引器在getSectionForPosition返回 0 时工作正常?

public int getSectionForPosition(int position) {
    return 0;
}

许多教程中都使用了这个实现,例如:

http://androidopentutorials.com/android-listview-fastscroll/

http://www.survivingwithandroid.com/2012/12/android-listview-sectionindexer-fastscroll.html

文档说

给定适配器内的一个位置,返回相应部分在部分对象数组中的索引。

所以如果我的列表有 5 个以字母“A”开头的项目和一些以字母“B”开头的项目,那么 getSectionForPosition(5) 应该返回 1。

4

2 回答 2

3

虽然sectionIndexer(在拉动滚动条拇指时滚动部分索引)的基本功能不受影响,但在方法中返回一个常量getSectionForPosition可能会导致在滑动列表时出现滚动条定位的错误行为(例如,滚动条移出窗口在 y 轴上)。

显然,这种不当行为仅在列表或单个部分超过一定长度时才会发生,因此对于较短的列表,索引器似乎可以正常工作(但实际上没有)。在上述方法中多次返回常量时,我​​在较大的列表中遇到了这种不当行为,并通过getSectionForPosition以正确的方式实现来修复它。


但是,由于其他人可能会感兴趣,因此我可以提供该方法的示例实现。让azIndexeraHashMap包含section -> position我的索引的正确映射,并listItems成为适配器排列的项目。以下构建position -> sectionIndex存储在positionIndexer.

List<Integer> values = new ArrayList();
for (int i : azIndexer.values()) {
    values.add(i);
}
values.add(listItems.size()-1);
Collections.sort(values);

int k = 0;
int z = 0;
for(int i = 0; i < values.size()-1; i++) {
    int temp = values.get(i+1);
    do {
        positionIndexer.put(k, z);
        k++;
    } while(k < temp);
    z++;
}

然后将在getSectionForPosition方法中使用:

@Override
public int getSectionForPosition(int position) {
    return positionIndexer.get(position);
}
于 2015-03-28T15:25:11.777 回答
0

您的回调方法 getPositionForSection(int section) 需要实现以提供正确的位置,setSelection 使用该位置返回您想要在右侧的 SectionIndexer 触摸时滚动的正确位置。

确保你正在这样做

this.setSelection(((SectionIndexer) getAdapter()) .getPositionForSection(currentPosition));

你需要实现两个回调方法

@Override
public Object[] getSections() { 
  Log.d("ListView", "Get sections"); 
  String[] sectionsArr = new String[sections.length()]; 
  for (int i=0; i < sections.length(); i++) 
  sectionsArr[i] = "" + sections.charAt(i);

   return sectionsArr; 
 }

这个最后的回调,你在这里完成

@Override 
public int getPositionForSection(int section){ 
  Log.d("ListView", "Get position for section"); 
  for (int i=0; i < this.getCount(); i++) { 
  String item = this.getItem(i).toLowerCase(); 
  if (item.charAt(0) == sections.charAt(section)) 

 return i; 
} 

return 0; 
}
于 2015-03-30T10:40:55.903 回答