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

封面

轉(zhuǎn)載請(qǐng)注明出處:http://www.itdecent.cn/p/b753c4a9ddfa

本文出自 容華謝后的博客

1.寫在前面

SeekBar控件在開發(fā)中還是比較常見的,比如音視頻進(jìn)度、音量調(diào)節(jié)等,但是原生控件有時(shí)還不能滿足我們的需求,今天就來學(xué)習(xí)一下如何自定義SeekBar控件,本文主要實(shí)現(xiàn)了一個(gè)帶文字指示器效果的SeekBar控件,看下最終效果:

IndicatorSeekBar

2.實(shí)現(xiàn)

IndicatorSeekBar

public class IndicatorSeekBar extends AppCompatSeekBar {

    // 畫筆
    private Paint mPaint;
    // 進(jìn)度文字位置信息
    private Rect mProgressTextRect = new Rect();
    // 滑塊按鈕寬度
    private int mThumbWidth = dp2px(50);
    // 進(jìn)度指示器寬度
    private int mIndicatorWidth = dp2px(50);
    // 進(jìn)度監(jiān)聽
    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));

        // 如果不設(shè)置padding,當(dāng)滑動(dòng)到最左邊或最右邊時(shí),滑塊會(huì)顯示不全
        setPadding(mThumbWidth / 2, 0, mThumbWidth / 2, 0);

        // 設(shè)置滑動(dòng)監(jiān)聽
        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);

        // 進(jìn)度百分比
        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);
        }
    }

    /**
     * 設(shè)置進(jìn)度監(jiān)聽
     *
     * @param listener OnIndicatorSeekBarChangeListener
     */
    public void setOnSeekBarChangeListener(OnIndicatorSeekBarChangeListener listener) {
        this.mIndicatorSeekBarChangeListener = listener;
    }

    /**
     * 進(jìn)度監(jiān)聽
     */
    public interface OnIndicatorSeekBarChangeListener {
        /**
         * 進(jìn)度監(jiān)聽回調(diào)
         *
         * @param seekBar         SeekBar
         * @param progress        進(jìn)度
         * @param indicatorOffset 指示器偏移量
         */
        public void onProgressChanged(SeekBar seekBar, int progress, float indicatorOffset);

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

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

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

    /**
     * sp轉(zhuǎn)px
     *
     * @param sp sp值
     * @return px值
     */
    private int sp2px(float sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                getResources().getDisplayMetrics());
    }
}

重點(diǎn)看下onDraw方法:

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

    // 進(jìn)度百分比
    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

可以看到,進(jìn)度百分比文字是跟著進(jìn)度變化在平移的,所以X軸坐標(biāo)根據(jù)進(jìn)度動(dòng)態(tài)計(jì)算就可以了【總寬度 * 進(jìn)度百分比】(getWidth() * progressRatio),文字需要居中顯示,所以需要向右平移【(滑塊寬度 - 文字寬度)/ 2】((mThumbWidth - mProgressTextRect.width()) / 2)。

為了避免滑塊滑動(dòng)到終點(diǎn)時(shí)布局被隱藏,需要為SeekBar設(shè)置左右padding,距離分別為滑塊寬度的一半,,所以【控件總長(zhǎng)度 = 控件實(shí)際長(zhǎng)度 + 滑塊寬度】,向右平移的過程中就要?jiǎng)討B(tài)減去滑塊寬度【滑塊寬度 * 進(jìn)度百分比】(mThumbWidth * progressRatio),到這里文字的X軸坐標(biāo)就計(jì)算完成了。

文字在平移的過程中始終是垂直居中的,所以Y軸坐標(biāo)可以這樣計(jì)算【控件高度 / 2 + 文字高度 / 2】(getHeight() / 2f + mProgressTextRect.height() / 2f),注意drawText方法默認(rèn)是從左下角開始繪制文字的,如果對(duì)繪制文字還不太了解,可以看下這篇文章《Android 圖解Canvas drawText文字居中的那些事》

指示器跟隨滑塊移動(dòng)

在IndicatorSeekBar中,向外提供了一個(gè)setOnSeekBarChangeListener方法用來回調(diào)SeekBar的狀態(tài),其中onProgressChanged方法中的indicatorOffset參數(shù)就是指示器控件的X坐標(biāo),計(jì)算方式與上文中進(jìn)度百分比文字的計(jì)算方式一致:

// 【總寬度 * 進(jìn)度百分比 -(指示器寬度 - 滑塊寬度)/ 2 - 滑塊寬度 * 進(jìn)度百分比】
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地址:https://github.com/alidili/Demos/tree/master/IndicatorSeekBarDemo

本文Demo的Apk下載地址:https://github.com/alidili/Demos/raw/master/IndicatorSeekBarDemo/IndicatorSeekBarDemo.apk

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、前言 最近項(xiàng)目里面需要用到多個(gè)seekbar并且需要顯示不同的精度,于是參考了部分博客模仿華為的天氣刻度盤添加...
    IT魔幻師閱讀 9,983評(píng)論 3 83
  • 我旅行的時(shí)間很長(zhǎng),旅途也很長(zhǎng)。 過去幾天了,還記得你哭紅的雙眼,蹲在比賽點(diǎn),你無助地望向我,然后像小鹿一樣...
    Li三金閱讀 473評(píng)論 3 2
  • “上進(jìn)心”,就是在現(xiàn)有的認(rèn)識(shí)當(dāng)中,比別人過得好。不僅過得好,而且要讓別人都知道,才是全面的好。
    對(duì)你說真的閱讀 222評(píng)論 0 0
  • 今天是《斷舍離》修煉第六天,今天的閱讀內(nèi)容:第一章的“東西要用才有價(jià)值”;今天的思考是開放性的,經(jīng)過第一章學(xué)習(xí),您...
    小鼻豬閱讀 237評(píng)論 0 0

友情鏈接更多精彩內(nèi)容