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

IndicatorSeekBar
2.實現(xiàn)
IndicatorSeekBar
public class IndicatorSeekBar extends AppCompatSeekBar {
// 畫筆
private Paint mPaint;
// 進度文字位置信息
private Rect mProgressTextRect = new Rect();
// 滑塊按鈕寬度
private int mThumbWidth = dp2px(50);
// 進度指示器寬度
private int mIndicatorWidth = dp2px(50);
// 進度監(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,當滑動到最左邊或最右邊時,滑塊會顯示不全
setPadding(mThumbWidth / 2, 0, mThumbWidth / 2, 0);
// 設(shè)置滑動監(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);
// 進度百分比
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è)置進度監(jiān)聽
*
* @param listener OnIndicatorSeekBarChangeListener
*/
public void setOnSeekBarChangeListener(OnIndicatorSeekBarChangeListener listener) {
this.mIndicatorSeekBarChangeListener = listener;
}
/**
* 進度監(jiān)聽
*/
public interface OnIndicatorSeekBarChangeListener {
/**
* 進度監(jiān)聽回調(diào)
*
* @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轉(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());
}
}
重點看下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軸坐標根據(jù)進度動態(tài)計算就可以了【總寬度 * 進度百分比】(getWidth() * progressRatio),文字需要居中顯示,所以需要向右平移【(滑塊寬度 - 文字寬度)/ 2】( (mThumbWidth - mProgressTextRect.width()) / 2)。
為了避免滑塊滑動到終點時布局被隱藏,需要為SeekBar設(shè)置左右padding,距離分別為滑塊寬度的一半,,所以【控件總長度 = 控件實際長度 + 滑塊寬度】,向右平移的過程中就要動態(tài)減去滑塊寬度【滑塊寬度 * 進度百分比】(mThumbWidth * progressRatio),到這里文字的X軸坐標就計算完成了。
文字在平移的過程中始終是垂直居中的,所以Y軸坐標可以這樣計算【控件高度 / 2 + 文字高度 / 2】(getHeight() / 2f + mProgressTextRect.height() / 2f),注意drawText方法默認是從左下角開始繪制文字的,如果對繪制文字還不太了解,可以看下這篇文章《Android 圖解Canvas drawText文字居中的那些事》
指示器跟隨滑塊移動
在IndicatorSeekBar中,向外提供了一個setOnSeekBarChangeListener方法用來回調(diào)SeekBar的狀態(tài),其中onProgressChanged方法中的indicatorOffset參數(shù)就是指示器控件的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地址:https://github.com/alidili/Demos/tree/master/IndicatorSeekBarDemo
本文Demo的Apk下載地址:
https://github.com/alidili/Demos/raw/master/IndicatorSeekBarDemo/IndicatorSeekBarDemo.apk
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Android基于OpenGL在GLSurfaceView上繪制三角形及使用投影和相機視圖方法示例
這篇文章主要介紹了Android基于OpenGL在GLSurfaceView上繪制三角形及使用投影和相機視圖方法,結(jié)合實例形式分析了Android基于OpenGL的圖形繪制技巧,需要的朋友可以參考下2016-10-10
為Android系統(tǒng)添加config.xml 新配置的設(shè)置
這篇文章主要介紹了為Android系統(tǒng)添加config.xml 新配置的設(shè)置,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Kotlin高效實現(xiàn) Android ViewPager2 頂部導(dǎo)航之動態(tài)配置與性能優(yōu)化指
文章介紹了使用AndroidViewPager2和TabLayout實現(xiàn)高效頂部導(dǎo)航的方法,并提供了優(yōu)化指南,包括避免不必要的Fragment實例化、動態(tài)配置頁面、使用Kotlin特性減少冗余代碼等,通過這些優(yōu)化,代碼變得更加高效、簡潔和易于維護,感興趣的朋友跟隨小編一起看看吧2025-03-03
Android實現(xiàn)布局動畫和共享動畫的結(jié)合效果
今天給大家?guī)砟軌蛱嵘脩趔w驗感的交互動畫,使用起來非常簡單,體驗效果非常贊,其中僅使用到布局動畫和共享動畫,文章通過代碼示例介紹的非常詳細,感興趣的同學(xué)可以自己動手試一試2023-09-09
android調(diào)用國家氣象局天氣預(yù)報接口json數(shù)據(jù)格式解釋
平時我們在開發(fā)的過程中有時會要用到天氣預(yù)報的信息,國家氣象局為我們提供了天氣預(yù)報的接口,只需要我們?nèi)ソ馕鼍托辛?。很方便很好?/div> 2013-11-11
Android 自定義view模板并實現(xiàn)點擊事件的回調(diào)
這篇文章主要介紹了Android 自定義view模板并實現(xiàn)點擊事件的回調(diào)的相關(guān)資料,需要的朋友可以參考下2017-01-01
關(guān)于AndroidStudio新建與編譯項目速度慢解決辦法
這篇文章主要介紹了關(guān)于AndroidStudio新建與編譯項目速度慢的解決辦法,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10最新評論

