天天看點

[Android執行個體] 側邊字母滑動檢索控件

該篇文章從eoeAndroid搬遷過來的,原文位址:[Android執行個體] 側邊字母滑動檢索控件

自定義側邊滑動檢索控件,能根據A~Z字母進行檢索,類似微信,通訊錄右側字母檢索方式

主要代碼:

@Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        // 擷取焦點改變背景顔色
        int height = getHeight();
        int width = getWidth();
        int sigleHeight = height / b.length;
        for (int i = ; i < b.length; i++) {
            paint.setColor(Color.BLACK);
            paint.setTypeface(Typeface.DEFAULT_BOLD);
            paint.setAntiAlias(true);
            paint.setTextSize();
            // 選中狀态
            if (i == position) {
                paint.setColor(Color.BLUE);
                paint.setTextSize();
                paint.setFakeBoldText(true);
            }
            // x坐标等于中間-字元串寬度的一半.
            float xPos = width /  - paint.measureText(b[i]) / ;
            float yPos = sigleHeight * i + sigleHeight;
            canvas.drawText(b[i], xPos, yPos, paint);
            paint.reset();// 重置畫筆
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        int action = event.getAction();
        float y = event.getY() - getY();
        int oldPosition = position;
        // 點選y坐标所占總高度的比例*b數組的長度就等于點選b中的個數.
        int c = ;
        if (y >=  && y <= getHeight()) {
            c = (int) (y / getHeight() * b.length);
        } else if (y > getHeight()) {
            c = b.length - ;
        }
        if (action == MotionEvent.ACTION_UP) {
            setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            position = -;
            if (showChooseText != null) {
                showChooseText.setVisibility(View.INVISIBLE);
            }
        } else {
            setBackgroundDrawable(new ColorDrawable(Color.GRAY));
            setBackgroundColor(Color.GRAY);
            if (oldPosition != c) {
                if (c >=  && c < b.length) {
                    if (onTouchingChangedListener != null) {
                        onTouchingChangedListener.onTouchingChanged(b[c]);
                    }
                }
                if (showChooseText != null) {
                    showChooseText.setText(b[c]);
                    showChooseText.setVisibility(View.VISIBLE);
                }
                position = c;
            }
        }
        invalidate();
        return true;
    }
           
[Android執行個體] 側邊字母滑動檢索控件
[Android執行個體] 側邊字母滑動檢索控件

下載下傳位址:項目代碼