最近做项目中需要用到拖动条,并且拖动条只能在某些值之间,于是找了点资料。
SeekBar
SeekBar通过设置Widget.AppCompat.SeekBar.Discrete主题可以实现离散值选择。
<androidx.appcompat.widget.AppCompatSeekBar
android:id="@+id/seekBar"
style="@style/Widget.AppCompat.SeekBar.Discrete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="4"
android:maxHeight="4dp"
android:progress="3"
android:progressDrawable="@drawable/progress"
android:thumb="@drawable/thumb"
app:tickMark="@drawable/tickmark" />
对应的progress.xml资源:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="20dp" />
<solid android:color="#DCDCDC" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="20dp" />
<solid android:color="#A7F2AA" />
</shape>
</clip>
</item>
</layer-list>
对应的thumb.xml资源:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#BBEEBD" />
<size
android:width="15dp"
android:height="15dp" />
</shape>
</item>
<item
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp">
<shape android:shape="oval">
<solid android:color="#21B827" />
<size
android:width="10dp"
android:height="10dp" />
</shape>
</item>
</layer-list>
对应的tickmark.xml资源:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#72EA77" />
<size
android:width="10dp"
android:height="10dp" />
</shape>
Slider
Slider是Material Design库中的控件。具体引入方式如下:
implementation 'com.google.android.material:material:1.4.0'
Slider既可以用作连续滑块,也可以用作离散滑块。操作模式由步长的值控制。如果步长设置为 0,则滑块作为连续滑块运行,滑块可以沿水平线移动到任何位置。如果步长设置为大于 0 的数字,则滑块作为离散滑块运行,滑块将捕捉到最接近的有效值。 Slider在滑动时可以展示指示标签。LabelFormatter接口用于定义在交互时呈现在指示标签内文本的格式。 使用默认样式com.google.android.material.R.style#Widget_MaterialComponents_Slider,使用colorPrimary和colorOnPrimary自定义滑块的颜色,使用colorOnSurface定义禁用状态颜色。以下属性用于进一步自定义滑块的外观:
- haloColor:thumb周围光环的颜色
- haloRadius:thumb周围光环的半径
- labelBehavior:标签的行为,可以是LABEL_FLOATING,LABEL_WITHIN_BOUNDS或LABEL_GONE
- labelStyle:应用于值指示器TooltipDrawable的样式
- thumbColor:thumb的颜色
- thumbStrokeColor:thumb的描边颜色
- thumbStrokeWidth:thumb的描边宽度
- thumbElevation:thumb的描边高度
- thumbRadius:thumb的半径
- tickColorActive:滑过部分的刻度颜色。仅在滑块处于离散模式时使用
- tickColorInactive:滑块未滑过部分的刻度线颜色。仅在滑块处于离散模式时使用
- tickColor:滑块刻度线的颜色。仅当滑块在离散模式。当tickColorActive和tickColorInactive相同时可以只设置此值,优先于tickColorActive和tickColorInactive
- tickVisible:是否显示刻度线。仅当滑块在离散模式
- trackColorActive:轨道滑过部分的颜色
- trackColorInactive:轨道未滑过部分的颜色
- trackColor:整个轨道的颜色。 当trackColorActive和trackColorInactive相同时可以只设置此值。优先于trackColorActive和trackColorInactive
- trackHeight:轨道高度
- android:valueFrom:必需。滑块的最小值,此值必须小于valueTo
- android:valueTo:必需。滑块的最大值,此值必须大于valueFrom
- android:value:可选。滑块的初始值
- android:stepSize:可选。该值表示滑块是否操作在连续模式或离散模式下。如果缺失或等于 0,则滑块在连续模式。如果大于0并均匀划分valueFrom和valueTo,滑块在离散模式下运行
对应的使用方式如下:
<com.google.android.material.slider.Slider
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stepSize="1"
android:value="3"
android:valueFrom="0"
android:valueTo="4"
app:haloColor="@color/black"
app:haloRadius="8dp"
app:thumbColor="#60C664"
app:thumbRadius="8dp"
app:tickColor="#60C664"
app:tickColorActive="#22B528"
app:tickColorInactive="#A0AAA0"
app:tickVisible="true"
app:trackColor="#60C664"
app:trackColorActive="#22B528"
app:trackColorInactive="#A0AAA0"
app:trackHeight="4dp" />
自定义控件
通过继承View进行自定义离散滑动控件。
public class DiscreteSeekBar extends View {
public interface OnDiscreteValueChangedListener {
void onValueChanged(DiscreteSeekBar seekBar, int value);
}
private Drawable mThumb;
private Drawable mTrackActive;
private Drawable mTrackInactive;
private Drawable mTickMarkActive;
private Drawable mTickMarkInactive;
private int mTrackHeight;
private int mLabelTextColor;
private int mLabelTextSize;
private int mLabelPadding;
private List<Rect> mTickRectList = new ArrayList<>();
private List<String> mTickLabelList = new ArrayList<>();
private int mLabelCount = 0;
private Paint mPaint;
private Paint mLabelPaint;
private int mValue;
private int mValueFrom;
private int mValueTo;
private int mStepSize;
private Rect mRect = new Rect();
private OnDiscreteValueChangedListener mOnDiscreteValueChangedListener;
public DiscreteSeekBar(Context context) {
this(context, null);
}
public DiscreteSeekBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DiscreteSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DiscreteSeekBar, defStyleAttr, 0);
mThumb = ta.getDrawable(R.styleable.DiscreteSeekBar_android_thumb);
mTrackActive = ta.getDrawable(R.styleable.DiscreteSeekBar_trackActive);
mTrackInactive = ta.getDrawable(R.styleable.DiscreteSeekBar_trackInactive);
mTickMarkActive = ta.getDrawable(R.styleable.DiscreteSeekBar_tickMarkActive);
mTickMarkInactive = ta.getDrawable(R.styleable.DiscreteSeekBar_tickMarkInactive);
mTrackHeight = ta.getDimensionPixelSize(R.styleable.DiscreteSeekBar_trackHeight, 4);
mLabelTextColor = ta.getColor(R.styleable.DiscreteSeekBar_labelTextColor, Color.BLACK);
mLabelTextSize = ta.getDimensionPixelSize(R.styleable.DiscreteSeekBar_labelTextSize, 16);
mLabelPadding = ta.getDimensionPixelSize(R.styleable.DiscreteSeekBar_labelPadding, 0);
mValueFrom = (int) ta.getFloat(R.styleable.DiscreteSeekBar_android_valueFrom, 0f);
mValueTo = (int) ta.getFloat(R.styleable.DiscreteSeekBar_android_valueTo, 10f);
mValue = (int) ta.getFloat(R.styleable.DiscreteSeekBar_android_value, mValueFrom);
mStepSize = (int) ta.getFloat(R.styleable.DiscreteSeekBar_android_stepSize, 1);
ta.recycle();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeWidth(mTrackHeight);
mPaint.setColor(Color.RED);
mLabelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mLabelPaint.setTextSize(mLabelTextSize);
mLabelPaint.setColor(mLabelTextColor);
}
public int getLabelPadding() {
return this.mLabelPadding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int dw = MeasureSpec.getSize(widthMeasureSpec);
int dh = MeasureSpec.getSize(heightMeasureSpec);
final Drawable d = mThumb;
if (d != null) {
dh = Math.max(dh, d.getIntrinsicHeight());
}
int labelHeight = 0;
if (mLabelCount != 0) {
Paint.FontMetrics fm = mLabelPaint.getFontMetrics();
labelHeight = (int) Math.ceil(fm.bottom - fm.top);
}
dh += getPaddingTop() + getPaddingBottom() + getLabelPadding() + labelHeight;
final int measuredWidth = resolveSizeAndState(dw, widthMeasureSpec, 0);
final int measuredHeight = resolveSizeAndState(dh, heightMeasureSpec, 0);
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mTickRectList.clear();
if (mThumb != null) {
final int count = getTickCount();
int tickPadding;
if (mLabelCount > 0) {
int start = Math.max((int) Math.ceil(mLabelPaint.measureText(mTickLabelList.get(0))), mThumb.getIntrinsicWidth()) >> 1;
int end = Math.max((int) Math.ceil(mLabelPaint.measureText(mTickLabelList.get(mLabelCount - 1))), mThumb.getIntrinsicWidth()) >> 1;
tickPadding = (w - start - end - getPaddingLeft() - getPaddingRight()) / (count - 1);
} else {
tickPadding = (w - mThumb.getIntrinsicWidth() - getPaddingLeft() - getPaddingRight()) / (count - 1);
}
for (int i = 0; i < count; i++) {
Rect rect = new Rect();
rect.left = getPaddingLeft() + tickPadding * i;
rect.top = getPaddingTop();
rect.right = rect.left + mThumb.getIntrinsicWidth();
rect.bottom = rect.top + mThumb.getIntrinsicHeight();
mTickRectList.add(rect);
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int activePosition = (mValue - mValueFrom) / mStepSize;
final int tickCount = getTickCount();
final int halfTrackHeight = mTrackHeight >> 1;
Rect startRect = mTickRectList.get(0);
Rect centerRect = mTickRectList.get(activePosition);
Rect endRect = mTickRectList.get(tickCount - 1);
if (activePosition != 0) {
mTrackActive.setBounds(startRect.centerX(), startRect.centerY() - halfTrackHeight, centerRect.centerX(), centerRect.centerY() + halfTrackHeight);
mTrackActive.draw(canvas);
}
if (activePosition != tickCount - 1) {
mTrackInactive.setBounds(centerRect.centerX(), centerRect.centerY() - halfTrackHeight, endRect.centerX(), endRect.centerY() + halfTrackHeight);
mTrackInactive.draw(canvas);
}
for (int i = 0; i < tickCount; i++) {
Rect rect = mTickRectList.get(i);
if (i < activePosition) {
setTickDrawableBound(mTickMarkActive, rect);
mTickMarkActive.draw(canvas);
} else if (i > activePosition) {
setTickDrawableBound(mTickMarkInactive, rect);
mTickMarkInactive.draw(canvas);
} else {
mThumb.setBounds(rect);
mThumb.draw(canvas);
}
}
if (mLabelCount > 0) {
drawLabel(canvas);
}
}
private void drawLabel(Canvas canvas) {
final int tickCount = getTickCount();
Rect rect;
String label;
Paint.FontMetrics fm = mLabelPaint.getFontMetrics();
final float baseline = (fm.bottom - fm.top) / 2 + (fm.descent - fm.ascent) / 2 - fm.descent;
for (int i = 0; i < tickCount; i++) {
label = getLabel(i);
rect = mTickRectList.get(i);
if (!TextUtils.isEmpty(label)) {
float labelWidth = mLabelPaint.measureText(label);
canvas.drawText(label, rect.centerX() - labelWidth / 2, rect.bottom + mLabelPadding + baseline, mLabelPaint);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < getTickCount(); i++) {
Rect rect = mTickRectList.get(i);
if (rect.contains((int) event.getX(), (int) event.getY())) {
return true;
}
}
} else if (action == MotionEvent.ACTION_UP) {
if (event.getEventTime() - event.getDownTime() < ViewConfiguration.getTapTimeout()) {
for (int i = 0; i < getTickCount(); i++) {
Rect rect = mTickRectList.get(i);
if (rect.contains((int) event.getX(), (int) event.getY())) {
mValue = mValueFrom + i * mStepSize;
invalidate();
break;
}
}
}
} else if (action == MotionEvent.ACTION_MOVE) {
final int x = (int) event.getX();
int index = 0;
int centerX = mTickRectList.get(0).centerX();
for (int i = 1, size = getTickCount(); i < size; i++) {
Rect rect = mTickRectList.get(i);
centerX = (centerX + rect.centerX()) >> 1;
if (x < centerX) {
index = i - 1;
break;
}
if (i == size - 1 && x >= centerX) {
index = i;
break;
}
centerX = rect.centerX();
}
final int value = mValueFrom + index * mStepSize;
if (value != mValue) {
mValue = value;
invalidate();
if (mOnDiscreteValueChangedListener != null) {
mOnDiscreteValueChangedListener.onValueChanged(this, value);
}
}
}
return super.onTouchEvent(event);
}
public void setLabelList(List<String> list) {
mTickLabelList.clear();
if (list != null) {
mTickLabelList.addAll(list);
}
mLabelCount = mTickLabelList.size();
requestLayout();
invalidate();
}
public void addLabel(String label) {
mTickLabelList.add(label);
mLabelCount = mTickLabelList.size();
requestLayout();
invalidate();
}
private String getLabel(int position) {
if (position < mLabelCount) {
return mTickLabelList.get(position);
}
return "";
}
public int getTickCount() {
return (mValueTo - mValueFrom) / mStepSize + 1;
}
private void setTickDrawableBound(Drawable drawable, Rect rect) {
if (drawable.getIntrinsicWidth() > 0 && drawable.getIntrinsicHeight() > 0) {
int dx = Math.max(rect.width() - drawable.getIntrinsicWidth(), 0) >> 1;
int dy = Math.max(rect.height() - drawable.getIntrinsicHeight(), 0) >> 1;
mRect.set(rect);
mRect.inset(dx, dy);
drawable.setBounds(mRect);
} else {
drawable.setBounds(rect);
}
}
public void setValue(int value) {
this.mValue = value;
invalidate();
}
public void setOnDiscreteValueChangedListener(OnDiscreteValueChangedListener listener) {
this.mOnDiscreteValueChangedListener = listener;
}
}
感谢大家的支持,如有错误请指正,如需转载请标明原文出处!
|