Android快速索引Demo

jopen 9年前


    最近需要实现一个城市列表的快速索引功能。类似于联系人应用,根据姓名首字母快速索引功能。

要实现这个功能只需要解决两个问题:

        1、对列表进行分组(具有同一特征),并且能够快速定位到该组的第一项
        2、右侧分组‘特征’快速索引栏的实现

    第一个问题比较好解决,列表项可以根据相同的‘特征’来分组,比如说城市列表可以根据相同首字母的城市名来进行分组。
如何来定位到分组的第一项,只需要把分组的‘特征’和分组第一项下标关联起来,快速索引栏就能快速定位分组第一项

    第二个问题可以通过自定义控件来实现,实现的形式有很多,可以通过绘制一整张分组‘特征’的图片(难以扩展),也可以动态来绘制每一个分组‘特征’(可扩展性强)

    下面是一些实现的关键代码,基本上就是上面思想的体现,如果自己有特殊的需求话,稍做改动就能行

    列表‘特征’和分组首项进行关联

    for (int i = 0; i < mCitys.size(); i++) {            City city = mCitys.get(i);            String cityId = city.getId();            if(cityId == null || "".equals(cityId)) continue;            String section = cityId.toUpperCase().substring(0, 1);            if(!indexMap.containsKey(section)){                indexMap.put(section, i);            }        }  

    快速索引的绘制
    @Override        protected void onDraw(Canvas canvas) {            heightCenter = getMeasuredHeight()/2 - preHeight*WORDS.length/2;            for (int i = 0; i < WORDS.length; i++) {                canvas.drawText(String.valueOf(WORDS[i]), getMeasuredWidth()/2, preHeight                        + (i * preHeight) + heightCenter, mPaint);            }            super.onDraw(canvas);        }  

    用户交互,快速定位到索引项
    public boolean onTouchEvent(MotionEvent event) {            int startY = (int) event.getY() - heightCenter;            int index = startY / preHeight;            if (index >= WORDS.length) {                index = WORDS.length - 1;            } else if (index < 0) {                index = 0;            }            if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {                int position = mSectionIndexter.getStartPositionOfSection(String.valueOf(WORDS[index]));                if (position == -1) {                    return true;                }                mListView.setSelection(position);            }            return true;        }  

    效果图如下:

20141225201301734.png

    

    源码:https://github.com/TUBB/CityIndex