【问题标题】:section indexer get section for position returns 0部分索引器获取位置的部分返回 0
【发布时间】:2015-03-05 08:15:17
【问题描述】:

在我的项目中,我有一个扩展 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。

【问题讨论】:

    标签: 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);
    }
    

    【讨论】:

    • (例如,滚动条在 y 轴上移出窗口)
    【解决方案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; 
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2013-10-16
      • 1970-01-01
      相关资源
      最近更新 更多