標籤:android
最近需要實現一個城市列表的快速索引功能。類似於連絡人應用,根據姓名首字母快速索引功能。
要實現這個功能只需要解決兩個問題:
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; }
如下:
源碼:https://github.com/TUBB/CityIndex
Android 快速索引(城市列表和連絡人)