Android 快速索引(城市列表和連絡人)

來源:互聯網
上載者:User

標籤: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 快速索引(城市列表和連絡人)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.