android 自定義範圍選取控制元件CustomRangeSeekBar

zyl409214686發表於2017-12-23

最近在做一款音樂剪下小工具, 需要用到一個範圍選取的控制元件。沒有合適的系統控制元件只能自定義一個。

效果圖:

test.gif

原始碼:

https://github.com/zyl409214686/CustomRangeSeekBar

實現思路

  1. 構造方法中初始化paint以及自定義屬性等其他引數。
  2. 重寫onMeasure方法確定view大小。
  3. 重寫onSizeChanged 方法初始化進度條rectF類物件。
  4. 重寫onDraw方法繪畫出進度以及滑塊和進度文字並將需要改變的引數改為變數。
  5. 重寫onTouchEvent處理檢測點選滑塊,以及相應的滑塊的滑動和觸發重繪等。

實現過程

1)初始化自定義屬性以及需要的各個引數。

 public CustomRangeSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomRangeSeekBar, 0, 0);
        this.mAbsoluteMinValue = new Float(a.getFloat(R.styleable.CustomRangeSeekBar_absoluteMin, (float) 0.0));
        this.mAbsoluteMaxValue = new Float(a.getFloat(R.styleable.CustomRangeSeekBar_absolutemMax, (float) 100.0));
        mThumbImage = BitmapFactory.decodeResource(getResources(), a.getResourceId(R.styleable.CustomRangeSeekBar_thumbImage, R.mipmap.btn_seekbar_normal));
        mProgressBarBg = BitmapFactory.decodeResource(getResources(), a.getResourceId(R.styleable.CustomRangeSeekBar_progressBarBg, R.mipmap.seekbar_bg));
        mProgressBarSelBg = BitmapFactory.decodeResource(getResources(), a.getResourceId(R.styleable.CustomRangeSeekBar_progressBarSelBg, R.mipmap.seekbar_sel_bg));
        mBetweenAbsoluteValue = a.getFloat(R.styleable.CustomRangeSeekBar_betweenAbsoluteValue, 0);
        mProgressTextFormat = a.getInt(R.styleable.CustomRangeSeekBar_progressTextFormat, HINT_FORMAT_NUMBER);
        mWordSize = a.getDimension(R.styleable.CustomRangeSeekBar_progressTextSize, 16);
        mPaint.setTextSize(mWordSize);
        mThumbWidth = mThumbImage.getWidth();
        mThumbHalfWidth = 0.5f * mThumbWidth;
        mThumbHalfHeight = 0.5f * mThumbImage.getHeight();
        mProgressBarHeight = 0.3f * mThumbHalfHeight;
        mWidthPadding = mThumbHalfHeight;
        Paint.FontMetrics metrics = mPaint.getFontMetrics();
        mWordHeight = (int) (metrics.descent - metrics.ascent);
        setPercentMinValue(0.0);
        setPercentMaxValue(100.0);
        a.recycle();
    }
複製程式碼

2)重寫onSizeChanged()方法中初始化進度條以及進度條被選中狀態的矩形區域。

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mProgressBarRect = new RectF(mWidthPadding, mWordHeight + 0.5f * (h - mWordHeight - mProgressBarHeight),
                w - mWidthPadding, mWordHeight + 0.5f*(h - mWordHeight + mProgressBarHeight));
        mProgressBarSelRect = new RectF(mProgressBarRect);
    }
複製程式碼

3)重寫onMeasure方法,設定view寬高。 View高度 = 滑塊高度+進度文字高度。

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MIN_WIDTH; if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) { width = MeasureSpec.getSize(widthMeasureSpec); } int height = mThumbImage.getHeight() + mWordHeight; if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) { height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec)); } setMeasuredDimension(width, height); }

4)重寫onDraw() 繪製進度、被選中範圍進度、兩個滑塊以及兩個滑塊對應的進度文字。

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // draw seek bar background line
        mPaint.setStyle(Style.FILL);
        canvas.drawBitmap(mProgressBarBg, null, mProgressBarRect, mPaint);
        // draw seek bar active range line
        mProgressBarSelRect.left = percentToScreen(mPercentMinValue);
        mProgressBarSelRect.right = percentToScreen(mPercentMaxValue);
        //canvas.drawBitmap(mProgressBarSelBg, mWidthPadding, 0.5f * (getHeight() - mProgressBarHeight), mPaint);
        canvas.drawBitmap(mProgressBarSelBg, null, mProgressBarSelRect, mPaint);
        // draw minimum thumb
        drawThumb(percentToScreen(mPercentMinValue), Thumb.MIN.equals(mPressedThumb), canvas);
        // draw maximum thumb
        drawThumb(percentToScreen(mPercentMaxValue), Thumb.MAX.equals(mPressedThumb), canvas);
        mPaint.setColor(Color.rgb(255, 165, 0));
//        mPaint.setTextSize(DensityUtils.dp2px(getContext(), 16));
        drawThumbMinText(percentToScreen(mPercentMinValue), getSelectedAbsoluteMinValue(), canvas);
        drawThumbMaxText(percentToScreen(mPercentMaxValue), getSelectedAbsoluteMaxValue(), canvas);
    }
複製程式碼

5)重寫onTouchEvent ()

@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mIsEnable)
            return true;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPressedThumb = evalPressedThumb(event.getX());
                if (Thumb.MIN.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onClickMinThumb(getSelectedAbsoluteMaxValue(), getSelectedAbsoluteMinValue());
                }
                if (Thumb.MAX.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onClickMaxThumb();
                }
                invalidate();
                //Intercept parent TouchEvent
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mPressedThumb != null) {
                    float eventX = event.getX();
                    float maxValue = percentToAbsoluteValue(mPercentMaxValue);
                    float minValue = percentToAbsoluteValue(mPercentMinValue);
                    float eventValue = percentToAbsoluteValue(screenToPercent(eventX));
                    if (Thumb.MIN.equals(mPressedThumb)) {
                        minValue = eventValue;
                        if (mBetweenAbsoluteValue>0 && maxValue - minValue <= mBetweenAbsoluteValue)
                            minValue = new Float((maxValue - mBetweenAbsoluteValue));
                        setPercentMinValue(absoluteValueToPercent(minValue));//Notice01
                        if (mThumbListener != null)
                            mThumbListener.onMinMove(getSelectedAbsoluteMaxValue(), getSelectedAbsoluteMinValue()); 
                    } else if (Thumb.MAX.equals(mPressedThumb)) {
                        maxValue = eventValue;
                        if (mBetweenAbsoluteValue>0 && maxValue - minValue <= mBetweenAbsoluteValue)
                            maxValue = new Float(minValue + mBetweenAbsoluteValue);
setPercentMaxValue(absoluteValueToPercent(maxValue));
                        if (mThumbListener != null)
                            mThumbListener.onMaxMove(getSelectedAbsoluteMaxValue(), getSelectedAbsoluteMinValue());
                    }
                }
                //Intercept parent TouchEvent
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (Thumb.MIN.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onUpMinThumb(getSelectedAbsoluteMaxValue(), getSelectedAbsoluteMinValue());
                }
                if (Thumb.MAX.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onUpMaxThumb();
                }
                //Intercept parent TouchEvent
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                if (Thumb.MIN.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onUpMinThumb(getSelectedAbsoluteMaxValue(), getSelectedAbsoluteMinValue());
                }
                if (Thumb.MAX.equals(mPressedThumb)) {
                    if (mThumbListener != null)
                        mThumbListener.onUpMaxThumb();
                }
                mPressedThumb = null;
                //Intercept parent TouchEvent
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
        }
        return true;
    }
複製程式碼

evalPressedThumb()方法為檢測事件源是否為滑塊(左or右or不在滑塊上)。其他還要一些轉換的方法percentToAbsoluteValue為進度條比例值轉換為具體值、 percentToAbsoluteValue為進度條的比例值轉換到具體值、screenToPercent為view中具體畫素轉換為進度中的進度條的比例值。 滑動事件處理邏輯,當檢測到滑動的為min滑塊(左測滑塊)時,看註釋Notice01 程式碼 setPercentMinValue(absoluteValueToPercent(minValue)); 將絕對值轉換為進度條比例,然後設定進去,看此方法。

    public void setPercentMinValue(double value) {
        mPercentMinValue = Math.max(0d, Math.min(1d, Math.min(value, mPercentMaxValue)));
        invalidate();
    }
複製程式碼

將比例值設定進去並呼叫了重繪,其他邏輯都大同小異,具體可以看上面留的github原始碼。

注意事項

事件處理的結尾需要增加對父容器view攔截的阻止。getParent().requestDisallowInterceptTouchEvent(true);不然滑動過程事件被父容器攔截而出現滑動不順暢的情況。 `

相關文章