在我的项目中,我有一个扩展ArrayAdapter<String>
并实现SectionIndexer
的类。在实现方法getPositionForSection
和getSectionForPosition
时,我发现了一些奇怪的行为。
当getSectionForPosition
返回0时,为什么section indexer正常工作?
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个以字母&#34开头的项目; A&#34;和一些以字母&#34; B&#34;开头的项目,然后getSectionForPosition(5)应该返回1.
答案 0 :(得分:3)
虽然sectionIndexer
的基本功能(在拉动滚动条拇指时滚动截面索引)不受影响,但在方法getSectionForPosition
中返回常量可能会导致滚动条定位不正常在列表中滑动(例如,滚动条在y轴上移出窗口)。
显然,这种不当行为只发生在列表或单个部分超过一定长度时,因此对于较短的列表,索引器似乎可能正常工作(但事实上并非如此)。在上述方法中多次返回常量并通过以正确的方式实现getSectionForPosition
来修复它时,我在较大的列表中遇到了这种不当行为。
然而,由于它可能对其他人感兴趣,我可以提供该方法的示例实现。让azIndexer
为HashMap
,其中包含我的索引的正确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);
}
答案 1 :(得分: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;
}