主要是继承SeekBar重新绘制滑块,在滑块上添加绘制文本,代码如下:
public class TextThumbSeekBar extends SeekBar { private int mThumbSize;//绘制滑块宽度 private TextPaint mTextPaint;//绘制文本的大小 private int mSeekBarMin=0;//滑块开始值 public TextThumbSeekBar(Context context) { this(context, null); } public TextThumbSeekBar(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.seekBarStyle); } public TextThumbSeekBar(Context context,AttributeSet attrs,int defStyleAttr){ super(context,attrs,defStyleAttr); mThumbSize=getResources().getDimensionPixelSize(R.dimen.width25); mTextPaint = new TextPaint(); mTextPaint.setColor(Color.WHITE); mTextPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.txtSize16)); mTextPaint.setTypeface(Typeface.DEFAULT_BOLD); mTextPaint.setTextAlign(Paint.Align.CENTER); } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); int unsignedMin = mSeekBarMin < 0 ? mSeekBarMin * -1 : mSeekBarMin; String progressText = String.valueOf(getProgress()+unsignedMin); Rect bounds = new Rect(); mTextPaint.getTextBounds(progressText, 0, progressText.length(), bounds); int leftPadding = getPaddingLeft() - getThumbOffset(); int rightPadding = getPaddingRight() - getThumbOffset(); int width = getWidth() - leftPadding - rightPadding; float progressRatio = (float) getProgress() / getMax(); float thumbOffset = mThumbSize * (.5f - progressRatio); float thumbX = progressRatio * width + leftPadding + thumbOffset; float thumbY = getHeight() / 2f + bounds.height() / 2f; canvas.drawText(progressText, thumbX, thumbY, mTextPaint); } public void setMix(int min){ mSeekBarMin=min; } }
在布局文件中添加:
<TextThumbSeekBar android:id="@+id/seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" android:maxHeight="4dp" android:minHeight="4dp" android:paddingLeft="@dimen/padding20" android:paddingRight="@dimen/padding20" android:thumb="@drawable/view_bar_progress_thumb"/>view_bar_progress_thumb.xml文件的样式为:
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" android:useLevel="false"> <solid android:color="#06a7fa"/> <size android:width="@dimen/width25" android:height="@dimen/height25"/> </shape>