【问题标题】:section indexer get section for position returns 0部分索引器获取位置的部分返回 0
【发布时间】:2015-03-05 08:15:17
【问题描述】:
【问题讨论】:
标签:
android
android-listview
android-arrayadapter
sectionindexer
【解决方案1】:
虽然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);
}
【解决方案2】:
您的回调方法 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;
}