Android開發(fā)雙向滑動選擇器范圍SeekBar實現(xiàn)
一、概述
之前公司app里面有個功能是一個可以雙向滑動的范圍選擇器,我在網(wǎng)上百度過一些實現(xiàn)方法,感覺各有利弊吧,但是都不太適合我們的需求。所以站在巨人的肩膀上,通過自定義View實現(xiàn)了一個可以適用于絕大多數(shù)情況的范圍選擇器來供大家使用。
首先,看效果圖:
我對該范圍選擇器的屬性進行了一些封裝,例如我們可以自由控制我們的范圍選擇器是否顯示刻度、刻度的長度、我們選擇器上每個值的單位、最大值最小值、游標(biāo)(即那個圓形圖片)的樣式、大小、選擇器內(nèi)部范圍顏色以及外部顏色等等很多屬性。更多玩法還請下載我的Demo體驗,項目地址在文末。
二、實現(xiàn)
2.1 首先看我們自定義View的全部代碼
public class DoubleSlideSeekBar extends View { /** * 線條(進度條)的寬度 */ private int lineWidth; /** * 線條(進度條)的長度 */ private int lineLength = 400; /** * 字所在的高度 100$ */ private int textHeight; /** * 游標(biāo) 圖片寬度 */ private int imageWidth; /** * 游標(biāo) 圖片高度 */ private int imageHeight; /** * 是否有刻度線 */ private boolean hasRule; /** * 左邊的游標(biāo)是否在動 */ private boolean isLowerMoving; /** * 右邊的游標(biāo)是否在動 */ private boolean isUpperMoving; /** * 字的大小 100$ */ private int textSize; /** * 字的顏色 100$ */ private int textColor; /** * 兩個游標(biāo)內(nèi)部 線(進度條)的顏色 */ private int inColor = Color.BLUE; /** * 兩個游標(biāo)外部 線(進度條)的顏色 */ private int outColor = Color.BLUE; /** * 刻度的顏色 */ private int ruleColor = Color.BLUE; /** * 刻度上邊的字 的顏色 */ private int ruleTextColor = Color.BLUE; /** * 左邊圖標(biāo)的圖片 */ private Bitmap bitmapLow; /** * 右邊圖標(biāo) 的圖片 */ private Bitmap bitmapBig; /** * 左邊圖標(biāo)所在X軸的位置 */ private int slideLowX; /** * 右邊圖標(biāo)所在X軸的位置 */ private int slideBigX; /** * 圖標(biāo)(游標(biāo)) 高度 */ private int bitmapHeight; /** * 圖標(biāo)(游標(biāo)) 寬度 */ private int bitmapWidth; /** * 加一些padding 大小酌情考慮 為了我們的自定義view可以顯示完整 */ private int paddingLeft = 100; private int paddingRight = 100; private int paddingTop = 50; private int paddingBottom = 10; /** * 線(進度條) 開始的位置 */ private int lineStart = paddingLeft; /** * 線的Y軸位置 */ private int lineY; /** * 線(進度條)的結(jié)束位置 */ private int lineEnd = lineLength + paddingLeft; /** * 選擇器的最大值 */ private int bigValue = 100; /** * 選擇器的最小值 */ private int smallValue = 0; /** * 選擇器的當(dāng)前最小值 */ private float smallRange; /** * 選擇器的當(dāng)前最大值 */ private float bigRange; /** * 單位 元 */ private String unit = " "; /** * 單位份數(shù) */ private int equal = 20; /** * 刻度單位 $ */ private String ruleUnit = " "; /** * 刻度上邊文字的size */ private int ruleTextSize = 20; /** * 刻度線的高度 */ private int ruleLineHeight = 20; private Paint linePaint; private Paint bitmapPaint; private Paint textPaint; private Paint paintRule; public DoubleSlideSeekBar(Context context) { this(context, null); } public DoubleSlideSeekBar(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public DoubleSlideSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DoubleSlideSeekBar, defStyleAttr, 0); int size = typedArray.getIndexCount(); for (int i = 0; i < size; i++) { int type = typedArray.getIndex(i); switch (type) { case R.styleable.DoubleSlideSeekBar_inColor: inColor = typedArray.getColor(type, Color.BLACK); break; case R.styleable.DoubleSlideSeekBar_lineHeight: lineWidth = (int) typedArray.getDimension(type, dip2px(getContext(), 10)); break; case R.styleable.DoubleSlideSeekBar_outColor: outColor = typedArray.getColor(type, Color.YELLOW); break; case R.styleable.DoubleSlideSeekBar_textColor: textColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_textSize: textSize = typedArray.getDimensionPixelSize(type, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; case R.styleable.DoubleSlideSeekBar_imageLow: bitmapLow = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(type, 0)); break; case R.styleable.DoubleSlideSeekBar_imageBig: bitmapBig = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(type, 0)); break; case R.styleable.DoubleSlideSeekBar_imageheight: imageHeight = (int) typedArray.getDimension(type, dip2px(getContext(), 20)); break; case R.styleable.DoubleSlideSeekBar_imagewidth: imageWidth = (int) typedArray.getDimension(type, dip2px(getContext(), 20)); break; case R.styleable.DoubleSlideSeekBar_hasRule: hasRule = typedArray.getBoolean(type, false); break; case R.styleable.DoubleSlideSeekBar_ruleColor: ruleColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_ruleTextColor: ruleTextColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_unit: unit = typedArray.getString(type); break; case R.styleable.DoubleSlideSeekBar_equal: equal = typedArray.getInt(type, 10); break; case R.styleable.DoubleSlideSeekBar_ruleUnit: ruleUnit = typedArray.getString(type); break; case R.styleable.DoubleSlideSeekBar_ruleTextSize: ruleTextSize = typedArray.getDimensionPixelSize(type, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; case R.styleable.DoubleSlideSeekBar_ruleLineHeight: ruleLineHeight = (int) typedArray.getDimension(type, dip2px(getContext(), 10)); break; case R.styleable.DoubleSlideSeekBar_bigValue: bigValue = typedArray.getInteger(type, 100); break; case R.styleable.DoubleSlideSeekBar_smallValue: smallValue = typedArray.getInteger(type, 100); break; default: break; } } typedArray.recycle(); init(); } private void init() { /**游標(biāo)的默認(rèn)圖*/ if (bitmapLow == null) { bitmapLow = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); } if (bitmapBig == null) { bitmapBig = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); } /**游標(biāo)圖片的真實高度 之后通過縮放比例可以把圖片設(shè)置成想要的大小*/ bitmapHeight = bitmapLow.getHeight(); bitmapWidth = bitmapLow.getWidth(); // 設(shè)置想要的大小 int newWidth = imageWidth; int newHeight = imageHeight; // 計算縮放比例 float scaleWidth = ((float) newWidth) / bitmapWidth; float scaleHeight = ((float) newHeight) / bitmapHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); /**縮放圖片*/ bitmapLow = Bitmap.createBitmap(bitmapLow, 0, 0, bitmapWidth, bitmapHeight, matrix, true); bitmapBig = Bitmap.createBitmap(bitmapBig, 0, 0, bitmapWidth, bitmapHeight, matrix, true); /**重新獲取游標(biāo)圖片的寬高*/ bitmapHeight = bitmapLow.getHeight(); bitmapWidth = bitmapLow.getWidth(); /**初始化兩個游標(biāo)的位置*/ slideLowX = lineStart; slideBigX = lineEnd; smallRange = smallValue; bigRange = bigValue; if (hasRule) { //有刻度時 paddingTop 要加上(text高度)和(刻度線高度加刻度線上邊文字的高度和) 之間的最大值 paddingTop = paddingTop + Math.max(textSize, ruleLineHeight + ruleTextSize); } else { //沒有刻度時 paddingTop 加上 text的高度 paddingTop = paddingTop + textSize; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getMyMeasureWidth(widthMeasureSpec); int height = getMyMeasureHeight(heightMeasureSpec); setMeasuredDimension(width, height); } private int getMyMeasureHeight(int heightMeasureSpec) { int mode = MeasureSpec.getMode(heightMeasureSpec); int size = MeasureSpec.getSize(heightMeasureSpec); if (mode == MeasureSpec.EXACTLY) { // matchparent 或者 固定大小 view最小應(yīng)為 paddingBottom + paddingTop + bitmapHeight + 10 否則顯示不全 size = Math.max(size, paddingBottom + paddingTop + bitmapHeight + 10); } else { //wrap content int height = paddingBottom + paddingTop + bitmapHeight + 10; size = Math.min(size, height); } return size; } private int getMyMeasureWidth(int widthMeasureSpec) { int mode = MeasureSpec.getMode(widthMeasureSpec); int size = MeasureSpec.getSize(widthMeasureSpec); if (mode == MeasureSpec.EXACTLY) { size = Math.max(size, paddingLeft + paddingRight + bitmapWidth * 2); } else { //wrap content int width = paddingLeft + paddingRight + bitmapWidth * 2; size = Math.min(size, width); } // match parent 或者 固定大小 此時可以獲取線(進度條)的長度 lineLength = size - paddingLeft - paddingRight - bitmapWidth; //線(進度條)的結(jié)束位置 lineEnd = lineLength + paddingLeft + bitmapWidth / 2; //線(進度條)的開始位置 lineStart = paddingLeft + bitmapWidth / 2; //初始化 游標(biāo)位置 slideBigX = lineEnd; slideLowX = lineStart; return size; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Y軸 坐標(biāo) lineY = getHeight() - paddingBottom - bitmapHeight / 2; // 字所在高度 100$ textHeight = lineY - bitmapHeight / 2 - 10; //是否畫刻度 if (hasRule) { drawRule(canvas); } if (linePaint == null) { linePaint = new Paint(); } //畫內(nèi)部線 linePaint.setAntiAlias(true); linePaint.setStrokeWidth(lineWidth); linePaint.setColor(inColor); linePaint.setStrokeCap(Paint.Cap.ROUND); canvas.drawLine(slideLowX, lineY, slideBigX, lineY, linePaint); linePaint.setColor(outColor); linePaint.setStrokeCap(Paint.Cap.ROUND); //畫 外部線 canvas.drawLine(lineStart, lineY, slideLowX, lineY, linePaint); canvas.drawLine(slideBigX, lineY, lineEnd, lineY, linePaint); //畫游標(biāo) if (bitmapPaint == null) { bitmapPaint = new Paint(); } canvas.drawBitmap(bitmapLow, slideLowX - bitmapWidth / 2, lineY - bitmapHeight / 2, bitmapPaint); canvas.drawBitmap(bitmapBig, slideBigX - bitmapWidth / 2, lineY - bitmapHeight / 2, bitmapPaint); //畫 游標(biāo)上邊的字 if (textPaint == null) { textPaint = new Paint(); } textPaint.setColor(textColor); textPaint.setTextSize(textSize); textPaint.setAntiAlias(true); canvas.drawText(String.format("%.0f" + unit, smallRange), slideLowX - bitmapWidth / 2, textHeight, textPaint); canvas.drawText(String.format("%.0f" + unit, bigRange), slideBigX - bitmapWidth / 2, textHeight, textPaint); } @Override public boolean onTouchEvent(MotionEvent event) { //事件機制 super.onTouchEvent(event); float nowX = event.getX(); float nowY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //按下 在線(進度條)范圍上 boolean rightY = Math.abs(nowY - lineY) < bitmapHeight / 2; //按下 在左邊游標(biāo)上 boolean lowSlide = Math.abs(nowX - slideLowX) < bitmapWidth / 2; //按下 在右邊游標(biāo)上 boolean bigSlide = Math.abs(nowX - slideBigX) < bitmapWidth / 2; if (rightY && lowSlide) { isLowerMoving = true; } else if (rightY && bigSlide) { isUpperMoving = true; //點擊了游標(biāo)外部 的線上 } else if (nowX >= lineStart && nowX <= slideLowX - bitmapWidth / 2 && rightY) { slideLowX = (int) nowX; updateRange(); postInvalidate(); } else if (nowX <= lineEnd && nowX >= slideBigX + bitmapWidth / 2 && rightY) { slideBigX = (int) nowX; updateRange(); postInvalidate(); } break; case MotionEvent.ACTION_MOVE: //左邊游標(biāo)是運動狀態(tài) if (isLowerMoving) { //當(dāng)前 X坐標(biāo)在線上 且在右邊游標(biāo)的左邊 if (nowX <= slideBigX - bitmapWidth && nowX >= lineStart - bitmapWidth / 2) { slideLowX = (int) nowX; if (slideLowX < lineStart) { slideLowX = lineStart; } //更新進度 updateRange(); postInvalidate(); } } else if (isUpperMoving) { //當(dāng)前 X坐標(biāo)在線上 且在左邊游標(biāo)的右邊 if (nowX >= slideLowX + bitmapWidth && nowX <= lineEnd + bitmapWidth / 2) { slideBigX = (int) nowX; if (slideBigX > lineEnd) { slideBigX = lineEnd; } //更新進度 updateRange(); postInvalidate(); } } break; //手指抬起 case MotionEvent.ACTION_UP: isUpperMoving = false; isLowerMoving = false; break; default: break; } return true; } private void updateRange() { //當(dāng)前 左邊游標(biāo)數(shù)值 smallRange = computRange(slideLowX); //當(dāng)前 右邊游標(biāo)數(shù)值 bigRange = computRange(slideBigX); //接口 實現(xiàn)值的傳遞 if (onRangeListener != null) { onRangeListener.onRange(smallRange, bigRange); } } /** * 獲取當(dāng)前值 */ private float computRange(float range) { return (range - lineStart) * (bigValue - smallValue) / lineLength + smallValue; } public int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 畫刻度 */ protected void drawRule(Canvas canvas) { if (paintRule == null) { paintRule = new Paint(); } paintRule.setStrokeWidth(1); paintRule.setTextSize(ruleTextSize); paintRule.setTextAlign(Paint.Align.CENTER); paintRule.setAntiAlias(true); //遍歷 equal份,畫刻度 for (int i = smallValue; i <= bigValue; i += (bigValue - smallValue) / equal) { float degX = lineStart + i * lineLength / (bigValue - smallValue); int degY = lineY - ruleLineHeight; paintRule.setColor(ruleColor); canvas.drawLine(degX, lineY, degX, degY, paintRule); paintRule.setColor(ruleTextColor); canvas.drawText(String.valueOf(i) + ruleUnit, degX, degY, paintRule); } } /** * 寫個接口 用來傳遞最大最小值 */ public interface onRangeListener { void onRange(float low, float big); } private onRangeListener onRangeListener; public void setOnRangeListener(DoubleSlideSeekBar.onRangeListener onRangeListener) { this.onRangeListener = onRangeListener; } }
2.2 實現(xiàn)流程
代碼的注解很詳細(xì),下面我們來進一步分析此自定義view的實現(xiàn)步驟。
首先,我們要自定義一些屬性,在res/values文件夾下創(chuàng)建文件attrs,內(nèi)容如下:
<resources> <!--線(進度條)寬度--> <attr name="lineHeight" format="dimension" /> <!--字的大小 100元--> <attr name="textSize" format="dimension" /> <!--字的顏色 100元--> <attr name="textColor" format="color" /> <!--兩個游標(biāo)內(nèi)部 線(進度條)的顏色--> <attr name="inColor" format="color" /> <!--兩個游標(biāo)外部 線(進度條)的顏色--> <attr name="outColor" format="color" /> <!--左邊圖標(biāo)的圖片--> <attr name="imageLow" format="reference"/> <!--右邊圖標(biāo) 的圖片--> <attr name="imageBig" format="reference"/> <!--游標(biāo) 圖片寬度--> <attr name="imagewidth" format="dimension" /> <!--游標(biāo) 圖片高度--> <attr name="imageheight" format="dimension" /> <!--是否有刻度線--> <attr name="hasRule" format="boolean" /> <!--刻度的顏色--> <attr name="ruleColor" format="color" /> <!--刻度上邊的字 的顏色--> <attr name="ruleTextColor" format="color" /> <!--單位 元--> <attr name="unit" format="string"/> <!--單位份數(shù)--> <attr name="equal" format="integer"/> <!--刻度單位 $--> <attr name="ruleUnit" format="string"/> <!--刻度上邊文字的size--> <attr name="ruleTextSize" format="dimension" /> <!--刻度線的高度--> <attr name="ruleLineHeight" format="dimension" /> <!--選擇器的最大值--> <attr name="bigValue" format="integer"/> <!--選擇器的最小值--> <attr name="smallValue" format="integer"/> <declare-styleable name="DoubleSlideSeekBar"> <attr name="lineHeight" /> <attr name="textSize" /> <attr name="textColor" /> <attr name="inColor" /> <attr name="outColor" /> <attr name="imageLow"/> <attr name="imageBig"/> <attr name="imagewidth" /> <attr name="imageheight" /> <attr name="hasRule" /> <attr name="ruleColor" /> <attr name="ruleTextColor" /> <attr name="unit" /> <attr name="equal" /> <attr name="ruleUnit" /> <attr name="ruleTextSize" /> <attr name="ruleLineHeight" /> <attr name="bigValue" /> <attr name="smallValue" /> </declare-styleable> </resources>
我們要先確定我們要控制的屬性。綜合下來,我們需要控制進度條的寬度(高)、顏色、游標(biāo)上邊字的大小、刻度上邊字的大小、顏色、是否有游標(biāo)等等功能,所有屬性及說明如下(可以酌情定制):
xml屬性 | 值 | 解釋 |
---|---|---|
lineHeight | dimension | 控制我們線(進度條)的寬(高)度(例20dp) |
textSize | dimension | 游標(biāo)上邊字的大?。ɡ?6sp) |
textColor | color | 游標(biāo)上邊字的顏色 (例#e40627) |
inColor | color | 兩個游標(biāo)之間進度條的顏色 (例#e40627) |
outColor | color | 兩個游標(biāo)外部(游標(biāo)到進度條兩端)進度條的顏色 (例#e40627) |
imageLow | reference | 左邊游標(biāo)的圖片 (例@mipmap/imgv_slide) |
imageBig | reference | 右邊游標(biāo)的圖片 (例@mipmap/imgv_slide) |
imagewidth | dimension | 游標(biāo)圖片的寬度 (例20dp) |
imagewidth | dimension | 游標(biāo)圖片的高度 (例20dp) |
hasRule | boolean | 是否有刻度線(例 true or false) |
ruleColor | color | 刻度線的顏色 (例#e40627) |
ruleTextColor | color | 刻度線上邊的字的顏色 (例#e40627) |
unit | string | 單位 (例 元) |
equal | integer | 單位份數(shù),把全部數(shù)據(jù)分成equal份(例smallValue是0,bigValue是100,equal是10,則每個刻度大小為(100-0)/10 =10) |
ruleUnit | string | 刻度上邊文字的單位 (例 $) |
ruleTextSize | dimension | 刻度上邊文字的大小 (例20sp) |
ruleLineHeight | dimension | 刻度線高度(例16dp) |
bigValue | integer | 選擇器的最大值 (例 100) |
smallValue | integer | 選擇器的最小值 (例 0) |
之后在自定義View里面獲取我們定義的屬性:
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DoubleSlideSeekBar, defStyleAttr, 0); int size = typedArray.getIndexCount(); for (int i = 0; i < size; i++) { int type = typedArray.getIndex(i); switch (type) { case R.styleable.DoubleSlideSeekBar_inColor: inColor = typedArray.getColor(type, Color.BLACK); break; case R.styleable.DoubleSlideSeekBar_lineHeight: lineWidth = (int) typedArray.getDimension(type, dip2px(getContext(), 10)); break; case R.styleable.DoubleSlideSeekBar_outColor: outColor = typedArray.getColor(type, Color.YELLOW); break; case R.styleable.DoubleSlideSeekBar_textColor: textColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_textSize: textSize = typedArray.getDimensionPixelSize(type, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; case R.styleable.DoubleSlideSeekBar_imageLow: bitmapLow = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(type, 0)); break; case R.styleable.DoubleSlideSeekBar_imageBig: bitmapBig = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(type, 0)); break; case R.styleable.DoubleSlideSeekBar_imageheight: imageHeight = (int) typedArray.getDimension(type, dip2px(getContext(), 20)); break; case R.styleable.DoubleSlideSeekBar_imagewidth: imageWidth = (int) typedArray.getDimension(type, dip2px(getContext(), 20)); break; case R.styleable.DoubleSlideSeekBar_hasRule: hasRule = typedArray.getBoolean(type, false); break; case R.styleable.DoubleSlideSeekBar_ruleColor: ruleColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_ruleTextColor: ruleTextColor = typedArray.getColor(type, Color.BLUE); break; case R.styleable.DoubleSlideSeekBar_unit: unit = typedArray.getString(type); break; case R.styleable.DoubleSlideSeekBar_equal: equal = typedArray.getInt(type, 10); break; case R.styleable.DoubleSlideSeekBar_ruleUnit: ruleUnit = typedArray.getString(type); break; case R.styleable.DoubleSlideSeekBar_ruleTextSize: ruleTextSize = typedArray.getDimensionPixelSize(type, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; case R.styleable.DoubleSlideSeekBar_ruleLineHeight: ruleLineHeight = (int) typedArray.getDimension(type, dip2px(getContext(), 10)); break; case R.styleable.DoubleSlideSeekBar_bigValue: bigValue = typedArray.getInteger(type, 100); break; case R.styleable.DoubleSlideSeekBar_smallValue: smallValue = typedArray.getInteger(type, 100); break; default: break; } } typedArray.recycle();
由于我們要使用的是三個參數(shù)的構(gòu)造器,所以對應(yīng)一參二參的構(gòu)造器進行如下設(shè)置:
public DoubleSlideSeekBar(Context context) { this(context, null); } public DoubleSlideSeekBar(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); }
初始化
/**游標(biāo)圖片的真實高度 之后通過縮放比例可以把圖片設(shè)置成想要的大小*/ bitmapHeight = bitmapLow.getHeight(); bitmapWidth = bitmapLow.getWidth(); // 設(shè)置想要的大小 int newWidth = imageWidth; int newHeight = imageHeight; // 計算縮放比例 float scaleWidth = ((float) newWidth) / bitmapWidth; float scaleHeight = ((float) newHeight) / bitmapHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); /**縮放圖片*/ bitmapLow = Bitmap.createBitmap(bitmapLow, 0, 0, bitmapWidth, bitmapHeight, matrix, true); bitmapBig = Bitmap.createBitmap(bitmapBig, 0, 0, bitmapWidth, bitmapHeight, matrix, true); /**重新獲取游標(biāo)圖片的寬高*/ bitmapHeight = bitmapLow.getHeight(); bitmapWidth = bitmapLow.getWidth(); /**初始化兩個游標(biāo)的位置*/ slideLowX = lineStart; slideBigX = lineEnd; smallRange = smallValue; bigRange = bigValue; if (hasRule) { //有刻度時 paddingTop 要加上(text高度)和(刻度線高度加刻度線上邊文字的高度和) 之間的最大值 paddingTop = paddingTop + Math.max(textSize, ruleLineHeight + ruleTextSize); } else { //沒有刻度時 paddingTop 加上 text的高度 paddingTop = paddingTop + textSize; }
通過Matrix對bitmap進行縮放,將游標(biāo)設(shè)置成我們想要的大小。初始化兩個游標(biāo)在雙向選擇器的兩頭,一般都是在最大值和最小值處的,若有特殊需求也可更改slideLowX和slideBigX進行設(shè)置。由于我們在計算自定義view的高度時,需要把刻度以及刻度上邊文字的高度算進去,所以有刻度時 paddingTop 要加上(text高度)和(刻度線高度加刻度線上邊文字的高度和) 之間的最大值,沒有刻度時 paddingTop 加上 text的高度。
計算寬高
計算View的高度:
int mode = MeasureSpec.getMode(heightMeasureSpec); int size = MeasureSpec.getSize(heightMeasureSpec); if (mode == MeasureSpec.EXACTLY) { // matchparent 或者 固定大小 view最小應(yīng)為 paddingBottom + paddingTop + bitmapHeight + 10 否則顯示不全 size = Math.max(size, paddingBottom + paddingTop + bitmapHeight + 10); } else { //wrap content int height = paddingBottom + paddingTop + bitmapHeight + 10; size = Math.min(size, height); }
當(dāng)mode == MeasureSpec.EXACTLY時,我們在布局文件中已經(jīng)固定了view的高度,但是view最小應(yīng)為 paddingBottom + paddingTop + bitmapHeight + 10 否則顯示不全。當(dāng)沒有固定大小時,一般是wrap content,那么它的高度應(yīng)為 paddingBottom + paddingTop + bitmapHeight + 10(+10只是為了能讓view所占的空間大一些而已,沒有特殊意義,可以不加)。
計算View的寬度:
int mode = MeasureSpec.getMode(widthMeasureSpec); int size = MeasureSpec.getSize(widthMeasureSpec); if (mode == MeasureSpec.EXACTLY) { size = Math.max(size, paddingLeft + paddingRight + bitmapWidth * 2); } else { //wrap content int width = paddingLeft + paddingRight + bitmapWidth * 2; size = Math.min(size, width); } // match parent 或者 固定大小 此時可以獲取線(進度條)的長度 lineLength = size - paddingLeft - paddingRight - bitmapWidth; //線(進度條)的結(jié)束位置 lineEnd = lineLength + paddingLeft + bitmapWidth / 2; //線(進度條)的開始位置 lineStart = paddingLeft + bitmapWidth / 2; //初始化 游標(biāo)位置 slideBigX = lineEnd; slideLowX = lineStart;
與計算高度同理,但此時,我們需要確定線(進度條)的長度,起始點。
onDraw 繪制進度條
畫兩個游標(biāo)之間的線:
linePaint.setAntiAlias(true); linePaint.setStrokeWidth(lineWidth); linePaint.setColor(inColor); linePaint.setStrokeCap(Paint.Cap.ROUND); canvas.drawLine(slideLowX, lineY, slideBigX, lineY, linePaint);
此線從(slideLowX,lineY)到(slideBigX,lineY),其中slideLowX,slideBigY已經(jīng)在計算寬度時賦值。lineY = getHeight() - paddingBottom - bitmapHeight / 2,即整個View的高度減paddingBottom再減bitmapHeight / 2(游標(biāo)圖的1/2高度),如果游標(biāo)高度比線寬小的話,則lineY = getHeight() - paddingBottom - lineWidth / 2,不過這種需求應(yīng)該很少。
畫兩個游標(biāo)到兩端的線:
linePaint.setColor(outColor); linePaint.setStrokeCap(Paint.Cap.ROUND); //畫 外部線 canvas.drawLine(lineStart, lineY, slideLowX, lineY, linePaint); canvas.drawLine(slideBigX, lineY, lineEnd, lineY, linePaint);
linePaint.setStrokeCap(Paint.Cap.ROUND)可以畫出帶圓角的線。之后要畫兩條線,一條是從線的起點到左邊游標(biāo)的中心。另一條是從右邊游標(biāo)的中心到線的終點。畫游標(biāo):
canvas.drawBitmap(bitmapLow, slideLowX - bitmapWidth / 2, lineY - bitmapHeight / 2, bitmapPaint); canvas.drawBitmap(bitmapBig, slideBigX - bitmapWidth / 2, lineY - bitmapHeight / 2, bitmapPaint);
即左邊游標(biāo)左部為slideLowX - bitmapWidth / 2,頂端在lineY - bitmapHeight / 2。右邊游標(biāo)同理。
畫游標(biāo)上邊的字:
textPaint.setColor(textColor); textPaint.setTextSize(textSize); textPaint.setAntiAlias(true); canvas.drawText(String.format("%.0f" + unit, smallRange), slideLowX - bitmapWidth / 2, textHeight, textPaint); canvas.drawText(String.format("%.0f" + unit, bigRange), slideBigX - bitmapWidth / 2, textHeight, textPaint);
字的位置控制在游標(biāo)的正上方。有其他需求可以在此處調(diào)整。
畫刻度線:
paintRule.setStrokeWidth(1); paintRule.setTextSize(ruleTextSize); paintRule.setTextAlign(Paint.Align.CENTER); paintRule.setAntiAlias(true); //遍歷 equal份,畫刻度 for (int i = smallValue; i <= bigValue; i += (bigValue - smallValue) / equal) { float degX = lineStart + i * lineLength / (bigValue - smallValue); int degY = lineY - ruleLineHeight; paintRule.setColor(ruleColor); canvas.drawLine(degX, lineY, degX, degY, paintRule); paintRule.setColor(ruleTextColor); canvas.drawText(String.valueOf(i) + ruleUnit, degX, degY, paintRule); }
我們已經(jīng)傳過來equal的值,即把所有數(shù)據(jù)分成equal份,每一份畫一個刻度。并在刻度上方寫上數(shù)字。如果有特殊需求,比如有的刻度線長有的刻度線短,則需要加個判斷,根據(jù)判斷的結(jié)果drawLine,不同的結(jié)果設(shè)置不同的高度。
事件監(jiān)聽
我們需要判斷我們觸摸屏幕時是否點擊在游標(biāo)上,是左邊游標(biāo)還是右邊游標(biāo)。此時則需要我們對點擊事件的監(jiān)聽。
判斷點擊位置的方法:
float nowX = event.getX(); float nowY = event.getY(); //按下 在游標(biāo)范圍上 boolean rightY = Math.abs(nowY - lineY) < bitmapHeight / 2; //按下 在左邊游標(biāo)上 boolean lowSlide = Math.abs(nowX - slideLowX) < bitmapWidth / 2; //按下 在右邊游標(biāo)上 boolean bigSlide = Math.abs(nowX - slideBigX) < bitmapWidth / 2; if (rightY && lowSlide) { isLowerMoving = true; } else if (rightY && bigSlide) { isUpperMoving = true; //點擊了游標(biāo)外部 的線上 } else if (nowX >= lineStart && nowX <= slideLowX - bitmapWidth / 2 && rightY) { slideLowX = (int) nowX; updateRange(); postInvalidate(); } else if (nowX <= lineEnd && nowX >= slideBigX + bitmapWidth / 2 && rightY) { slideBigX = (int) nowX; updateRange(); postInvalidate(); }
若Math.abs(nowY - lineY) < bitmapHeight / 2,則當(dāng)前點擊位置Y的坐標(biāo)在游標(biāo)上下頂點之間,此時可判定當(dāng)前點擊位置在Y軸方向上滿足點到了游標(biāo)。接下來判斷X軸,若Math.abs(nowX - slideLowX) < bitmapWidth / 2即當(dāng)前點擊位置X的坐標(biāo)在游標(biāo)的左右頂點之間,此時滿足當(dāng)前點擊到了左邊游標(biāo)的條件。我們此時才可以判定當(dāng)前點擊位置點在了左邊游標(biāo)上。右邊游標(biāo)的判定同理。完整的監(jiān)聽代碼請在文末上傳的項目中查看。
滑動狀態(tài)監(jiān)聽:
//左邊游標(biāo)是運動狀態(tài) if (isLowerMoving) { //當(dāng)前 X坐標(biāo)在線上 且在右邊游標(biāo)的左邊 if (nowX <= slideBigX - bitmapWidth && nowX >= lineStart - bitmapWidth / 2) { slideLowX = (int) nowX; if (slideLowX < lineStart) { slideLowX = lineStart; } //更新進度 updateRange(); postInvalidate(); } } else if (isUpperMoving) { //當(dāng)前 X坐標(biāo)在線上 且在左邊游標(biāo)的右邊 if (nowX >= slideLowX + bitmapWidth && nowX <= lineEnd + bitmapWidth / 2) { slideBigX = (int) nowX; if (slideBigX > lineEnd) { slideBigX = lineEnd; } //更新進度 updateRange(); postInvalidate(); }
如果經(jīng)判定,當(dāng)前點擊位置在左邊游標(biāo)上,且當(dāng)前坐標(biāo)在右邊游標(biāo)的左邊,并且在線的起點的右邊(當(dāng)然還得考慮到游標(biāo)圖片大小的影響,不能讓兩個游標(biāo)重合)(nowX <= slideBigX - bitmapWidth && nowX >= lineStart - bitmapWidth / 2),那么更新當(dāng)前slideLowX,更新進度,之后調(diào)用postInvalidate()刷新界面。更新進度:
private void updateRange() { //當(dāng)前 左邊游標(biāo)數(shù)值 smallRange = computRange(slideLowX); //當(dāng)前 右邊游標(biāo)數(shù)值 bigRange = computRange(slideBigX); //接口 實現(xiàn)值的傳遞 if (onRangeListener != null) { onRangeListener.onRange(smallRange, bigRange); } }
通過此方法獲取左右游標(biāo)上的數(shù)值,然后通過我們自己定義的接口進行值的傳遞。
computRange();
private float computRange(float range) { return (range - lineStart) * (bigValue - smallValue) / lineLength + smallValue; }
這個方法在我看來就是個數(shù)學(xué)題了。通過當(dāng)前長度占總長度的比例,再乘以數(shù)據(jù)的總數(shù),加上起點的數(shù)據(jù)(數(shù)據(jù)的最小值),就是我們當(dāng)前的數(shù)據(jù)了。
三、使用 布局文件
布局文件(有刻度線)
<com.example.txs.doubleslideseekbar.DoubleSlideSeekBar android:id="@+id/doubleslide_withrule" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" custom:lineHeight="6dp" custom:textSize="12sp" custom:textColor="#0628e4" custom:inColor="#f10a0a" custom:outColor="#af08e2" custom:imageLow="@mipmap/imgv_slide" custom:imageBig="@mipmap/imgv_slide" custom:imagewidth="20dp" custom:imageheight="20dp" custom:hasRule="true" custom:ruleColor="#0e0e0e" custom:ruleTextColor="#f74104" custom:unit="元" custom:equal="10" custom:ruleUnit="$" custom:ruleTextSize="8sp" custom:ruleLineHeight="10dp" />
布局文件(無刻度線)
<com.example.txs.doubleslideseekbar.DoubleSlideSeekBar android:id="@+id/doubleslide_withoutrule" android:layout_marginTop="40dp" android:layout_width="300dp" android:layout_height="wrap_content" custom:lineHeight="20dp" custom:textSize="16sp" custom:textColor="#e40627" custom:inColor="#0a40f1" custom:outColor="#ace208" custom:imageLow="@mipmap/imgv_slide" custom:imageBig="@mipmap/imgv_slide" custom:imagewidth="20dp" custom:imageheight="20dp" custom:hasRule="false" custom:bigValue="1000" custom:smallValue="0" />
這里面包含了我們自定義屬性的使用,又不懂得地方請看上方表格。
- 代碼中用法
public class MainActivity extends AppCompatActivity { private DoubleSlideSeekBar mDoubleslideWithrule; private DoubleSlideSeekBar mDoubleslideWithoutrule; private TextView mTvMinRule; private TextView mTvMaxRule; private TextView mTvMinWithoutRule; private TextView mTvMaxWithoutRule; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); setListener(); } private void setListener() { // 用法 mDoubleslideWithrule.setOnRangeListener(new DoubleSlideSeekBar.onRangeListener() { @Override public void onRange(float low, float big) { mTvMinRule.setText("最小值" + String.format("%.0f" , low)); mTvMaxRule.setText("最大值" + String.format("%.0f" , big)); } }); mDoubleslideWithoutrule.setOnRangeListener(new DoubleSlideSeekBar.onRangeListener() { @Override public void onRange(float low, float big) { mTvMinWithoutRule.setText("最小值" + String.format("%.0f" , low)); mTvMaxWithoutRule.setText("最大值" + String.format("%.0f" , big)); } }); } private void initView() { mDoubleslideWithrule = (DoubleSlideSeekBar) findViewById(R.id.doubleslide_withrule); mDoubleslideWithoutrule = (DoubleSlideSeekBar) findViewById(R.id.doubleslide_withoutrule); mTvMinRule = (TextView) findViewById(R.id.tv_min_rule); mTvMaxRule = (TextView) findViewById(R.id.tv_max_rule); mTvMinWithoutRule = (TextView) findViewById(R.id.tv_min_without_rule); mTvMaxWithoutRule = (TextView) findViewById(R.id.tv_max_without_rule); } }
用法很簡單,我們可以通過我們定義的接口獲取當(dāng)前范圍。
四、后記
此項目使用自定義view的知識比較多,大家若想鞏固自己的自定義view的知識可以拿這個項目來練練手,而且由于時間問題,此項目可優(yōu)化的地方還很多,比如再加一個屬性控制游標(biāo)上邊的文字在游標(biāo)上部,中部,下部。
滑動監(jiān)聽判斷tanα<1才判斷是游標(biāo)在滑動,控制不同長度的刻度線等。這些大家都可以根據(jù)自己的需求自由定制,我所實現(xiàn)的功能也只是符合大多數(shù)情況而已。
github項目地址:https://github.com/tangxuesong6/DoubleSlideSeekBar
以上就是Android開發(fā)雙向滑動范圍選擇器SeekBar實現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于Android雙向滑動SeekBar范圍的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android 數(shù)據(jù)庫文件存取至儲存卡的方法
這篇文章主要介紹了Android 數(shù)據(jù)庫文件存取至儲存卡的方法的相關(guān)資料,需要的朋友可以參考下2016-03-03Android多線程+單線程+斷點續(xù)傳+進度條顯示下載功能
這篇文章主要介紹了Android多線程+單線程+斷點續(xù)傳+進度條顯示下載功能,需要的朋友可以參考下2017-06-06Android設(shè)置默認(rèn)鎖屏壁紙接口的方法
這篇文章主要介紹了Android默認(rèn)鎖屏壁紙接口的設(shè)置方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01Android 仿日歷翻頁、仿htc時鐘翻頁、數(shù)字翻頁切換效果
這篇文章主要介紹了Android 仿日歷翻頁、仿htc時鐘翻頁、數(shù)字翻頁切換效果,需要的朋友可以參考下2017-07-07Android studio報錯:The emulator process for AVD (xxx) was kill
這篇文章主要介紹了Android studio報錯:The emulator process for AVD (xxx) was killed,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12Android裁剪圖片為圓形圖片的實現(xiàn)原理與代碼
這個方法是根據(jù)傳入的圖片的高度(height)和寬度(width)決定的,如果是 width <= height時,則會裁剪高度,裁剪的區(qū)域是寬度不變高度從頂部到寬度width的長度2013-01-01