带文字的seekbar : 自定义progressDrawable/thumb :解决显示不全
Posted Mars-xq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带文字的seekbar : 自定义progressDrawable/thumb :解决显示不全相关的知识,希望对你有一定的参考价值。
自定义view
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSeekBar;
public class TextSeekbar extends AppCompatSeekBar
// 画笔
private Paint mPaint;
// 进度文字位置信息
private final Rect mProgressTextRect = new Rect();
// 滑块按钮宽度
private int mThumbWidth = 100;
public TextSeekbar(@NonNull Context context)
this(context, null);
public TextSeekbar(@NonNull Context context, AttributeSet attrs)
this(context, attrs, -1);
public TextSeekbar(@NonNull Context context, AttributeSet attrs, int defStyleAttr)
super(context, attrs, defStyleAttr);
init();
private void init()
mPaint = new TextPaint();
mPaint.setAntiAlias(true);
mPaint.setColor(getResources().getColor(R.color.color_FF000000));
mPaint.setTextSize(getResources().getDimension(R.dimen.dp_19));
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
super.onSizeChanged(w, h, oldw, oldh);
// 若是不设置padding,当滑动到最左边或最右边时,滑块会显示不全
Drawable thumb = getThumb();
if (thumb != null)
mThumbWidth = thumb.getIntrinsicWidth();
setPadding(mThumbWidth / 2, 0, mThumbWidth / 2, 0);
@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.0f
- mThumbWidth * progressRatio;
float thumbX = getWidth() * progressRatio + thumbOffset;
float thumbY = getHeight() / 2f + mProgressTextRect.height() / 2f;
canvas.drawText(progressText, thumbX, thumbY, mPaint);
布局使用:
<TextSeekbar
android:id="@+id/textSeekbar"
android:layout_width="@dimen/dp_420"
android:layout_height="@dimen/dp_52"
android:layout_marginVertical="@dimen/dp_20"
android:max="360"
android:progressDrawable="@drawable/progress_drawable1"
android:thumb="@drawable/thumb1" />
drawable/progress_drawable1:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#993D4249" />
<corners android:radius="@dimen/dp_8" />
<size
android:width="@dimen/dp_420"
android:height="@dimen/dp_52" />
</shape>
drawable/thumb1:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFD4D8E1" />
<corners android:radius="@dimen/dp_8" />
<size
android:width="@dimen/dp_84"
android:height="@dimen/dp_52" />
</shape>
以上是关于带文字的seekbar : 自定义progressDrawable/thumb :解决显示不全的主要内容,如果未能解决你的问题,请参考以下文章