Android自定義控制元件 帶文字提示的SeekBar

容華謝後發表於2019-03-04

轉載請註明出處:juejin.im/post/5c1af0…

本文出自 容華謝後的部落格

1.寫在前面

SeekBar控制元件在開發中還是比較常見的,比如音視訊進度、音量調節等,但是原生控制元件有時還不能滿足我們的需求,今天就來學習一下如何自定義SeekBar控制元件,本文主要實現了一個帶文字指示器效果的SeekBar控制元件,看下最終效果:

IndicatorSeekBar

2.實現

IndicatorSeekBar

public class IndicatorSeekBar extends AppCompatSeekBar {

    // 畫筆
    private Paint mPaint;
    // 進度文字位置資訊
    private Rect mProgressTextRect = new Rect();
    // 滑塊按鈕寬度
    private int mThumbWidth = dp2px(50);
    // 進度指示器寬度
    private int mIndicatorWidth = dp2px(50);
    // 進度監聽
    private OnIndicatorSeekBarChangeListener mIndicatorSeekBarChangeListener;

    public IndicatorSeekBar(Context context) {
        this(context, null);
    }

    public IndicatorSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.seekBarStyle);
    }

    public IndicatorSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new TextPaint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#00574B"));
        mPaint.setTextSize(sp2px(16));

        // 如果不設定padding,當滑動到最左邊或最右邊時,滑塊會顯示不全
        setPadding(mThumbWidth / 2, 0, mThumbWidth / 2, 0);

        // 設定滑動監聽
        this.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // NO OP
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mIndicatorSeekBarChangeListener != null) {
                    mIndicatorSeekBarChangeListener.onStartTrackingTouch(seekBar);
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mIndicatorSeekBarChangeListener != null) {
                    mIndicatorSeekBarChangeListener.onStopTrackingTouch(seekBar);
                }
            }
        });
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        String progressText = getProgress() + "%";
        mPaint.getTextBounds(progressText, 0, progressText.length(), mProgressTextRect);

        // 進度百分比
        float progressRatio = (float) getProgress() / getMax();
        // thumb偏移量
        float thumbOffset = (mThumbWidth - mProgressTextRect.width()) / 2 - mThumbWidth * progressRatio;
        float thumbX = getWidth() * progressRatio + thumbOffset;
        float thumbY = getHeight() / 2f + mProgressTextRect.height() / 2f;
        canvas.drawText(progressText, thumbX, thumbY, mPaint);

        if (mIndicatorSeekBarChangeListener != null) {
            float indicatorOffset = getWidth() * progressRatio - (mIndicatorWidth - mThumbWidth) / 2 - mThumbWidth * progressRatio;
            mIndicatorSeekBarChangeListener.onProgressChanged(this, getProgress(), indicatorOffset);
        }
    }

    /**
     * 設定進度監聽
     *
     * @param listener OnIndicatorSeekBarChangeListener
     */
    public void setOnSeekBarChangeListener(OnIndicatorSeekBarChangeListener listener) {
        this.mIndicatorSeekBarChangeListener = listener;
    }

    /**
     * 進度監聽
     */
    public interface OnIndicatorSeekBarChangeListener {
        /**
         * 進度監聽回撥
         *
         * @param seekBar         SeekBar
         * @param progress        進度
         * @param indicatorOffset 指示器偏移量
         */
        public void onProgressChanged(SeekBar seekBar, int progress, float indicatorOffset);

        /**
         * 開始拖動
         *
         * @param seekBar SeekBar
         */
        public void onStartTrackingTouch(SeekBar seekBar);

        /**
         * 停止拖動
         *
         * @param seekBar SeekBar
         */
        public void onStopTrackingTouch(SeekBar seekBar);
    }

    /**
     * dp轉px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * sp轉px
     *
     * @param sp sp值
     * @return px值
     */
    private int sp2px(float sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                getResources().getDisplayMetrics());
    }
}
複製程式碼

重點看下onDraw方法:

@Override
protected synchronized void onDraw(Canvas canvas) {
	super.onDraw(canvas);
	String progressText = getProgress() + "%";
	mPaint.getTextBounds(progressText, 0, progressText.length(), mProgressTextRect);

	// 進度百分比
	float progressRatio = (float) getProgress() / getMax();
	// thumb偏移量
	float thumbOffset = (mThumbWidth - mProgressTextRect.width()) / 2 - mThumbWidth * progressRatio;
	float thumbX = getWidth() * progressRatio + thumbOffset;
	float thumbY = getHeight() / 2f + mProgressTextRect.height() / 2f;
	canvas.drawText(progressText, thumbX, thumbY, mPaint);

	if (mIndicatorSeekBarChangeListener != null) {
		float indicatorOffset = getWidth() * progressRatio - (mIndicatorWidth - mThumbWidth) / 2 - mThumbWidth * progressRatio;
		mIndicatorSeekBarChangeListener.onProgressChanged(this, getProgress(), indicatorOffset);
	}
}
複製程式碼

再看一遍效果圖:

IndicatorSeekBar

可以看到,進度百分比文字是跟著進度變化在平移的,所以X軸座標根據進度動態計算就可以了【總寬度 * 進度百分比】(getWidth() * progressRatio),文字需要居中顯示,所以需要向右平移【(滑塊寬度 – 文字寬度)/ 2】((mThumbWidth – mProgressTextRect.width()) / 2)。

為了避免滑塊滑動到終點時佈局被隱藏,需要為SeekBar設定左右padding,距離分別為滑塊寬度的一半,,所以【控制元件總長度 = 控制元件實際長度 + 滑塊寬度】,向右平移的過程中就要動態減去滑塊寬度【滑塊寬度 * 進度百分比】(mThumbWidth * progressRatio),到這裡文字的X軸座標就計算完成了。

文字在平移的過程中始終是垂直居中的,所以Y軸座標可以這樣計算【控制元件高度 / 2 + 文字高度 / 2】(getHeight() / 2f + mProgressTextRect.height() / 2f),注意drawText方法預設是從左下角開始繪製文字的,如果對繪製文字還不太瞭解,可以看下這篇文章《Android 圖解Canvas drawText文字居中的那些事》

指示器跟隨滑塊移動

在IndicatorSeekBar中,向外提供了一個setOnSeekBarChangeListener方法用來回撥SeekBar的狀態,其中onProgressChanged方法中的indicatorOffset引數就是指示器控制元件的X座標,計算方式與上文中進度百分比文字的計算方式一致:

// 【總寬度 * 進度百分比 -(指示器寬度 - 滑塊寬度)/ 2 - 滑塊寬度 * 進度百分比】
float indicatorOffset = getWidth() * progressRatio - (mIndicatorWidth - mThumbWidth) / 2 - mThumbWidth * progressRatio;
mIndicatorSeekBarChangeListener.onProgressChanged(this, getProgress(), indicatorOffset);
複製程式碼

看下如何使用:

public class MainActivity extends AppCompatActivity {

    private TextView tvIndicator;
    private IndicatorSeekBar indicatorSeekBar;
    private Paint mPaint = new Paint();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvIndicator = findViewById(R.id.tv_indicator);
        indicatorSeekBar = findViewById(R.id.indicator_seek_bar);

        initData();
    }

    private void initData() {
        final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvIndicator.getLayoutParams();
        indicatorSeekBar.setOnSeekBarChangeListener(new IndicatorSeekBar.OnIndicatorSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, float indicatorOffset) {
                String indicatorText = progress + "%";
                tvIndicator.setText(indicatorText);
                params.leftMargin = (int) indicatorOffset;
                tvIndicator.setLayoutParams(params);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                tvIndicator.setVisibility(View.VISIBLE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tvIndicator.setVisibility(View.INVISIBLE);
            }
        });
    }
}
複製程式碼

佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_indicator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/bg_indicator"
            android:gravity="center"
            android:textColor="#FFFFFF"
            android:textSize="16sp"
            android:visibility="invisible" />

        <com.yl.indicatorseekbar.IndicatorSeekBar
            android:id="@+id/indicator_seek_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@null"
            android:max="100"
            android:maxHeight="2dp"
            android:minHeight="2dp"
            android:progress="50"
            android:progressDrawable="@drawable/seekbar_progress_drawable"
            android:thumb="@drawable/seekbar_thumb" />

    </LinearLayout>

</RelativeLayout>

複製程式碼

3.寫在最後

程式碼已上傳至GitHub,歡迎Star、Fork!

GitHub地址:github.com/alidili/Dem…

本文Demo的Apk下載地址:github.com/alidili/Dem…

相關文章