本篇文章为大家展示了怎么在Android中利用View实现一个分段选择按钮,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1.1 获取item大小、起始位置
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if(isItemZero() || getMeasuredWidth() == 0) return; mHeight = getMeasuredHeight(); int width = getMeasuredWidth(); mItemWidth = (width - 2 * itemHorizontalMargin)/getCount(); mStart = itemHorizontalMargin + mItemWidth * selectedItem; mEnd = width - itemHorizontalMargin - mItemWidth; }
绘制背景,所有的Item,以及选中项
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if(isItemZero()) return; drawBackgroundRect(canvas); drawUnselectedItemsText(canvas); drawSelectedItem(canvas); drawSelectedItemsText(canvas); }
* 绘制背景区域
背景区域就是个带圆角的长方形
/** * 画背景区域 * @param canvas */ private void drawBackgroundRect(Canvas canvas) { float r = cornersMode == Round?cornersRadius: mHeight >> 1; mPaint.setXfermode(null); mPaint.setColor(backgroundColor); mRectF.set(0, 0, getWidth(), getHeight()); canvas.drawRoundRect(mRectF, r, r, mPaint); }
* 绘制所有未选中Item的文字
轮流绘制所有Item的文字
/** * 画所有未选中Item的文字 * @param canvas */ private void drawUnselectedItemsText(Canvas canvas) { mTextPaint.setColor(textColor); mTextPaint.setXfermode(null); for (int i = 0; i< getCount(); i++){ int start = itemHorizontalMargin + i * mItemWidth; float x = start + (mItemWidth >> 1) - mTextPaint.measureText(getName(i))/2; float y = (getHeight() >> 1) - (mTextPaint.ascent() + mTextPaint.descent())/2; canvas.drawText(getName(i), x, y, mTextPaint); } }
* 绘制选中项
/** * 画选中项 * @param canvas */ private void drawSelectedItem(Canvas canvas) { float r = cornersMode == Round?cornersRadius: (mHeight >> 1) - itemVerticalMargin; mPaint.setColor(selectedItemBackgroundColor); mRectF.set(mStart, itemVerticalMargin, mStart + mItemWidth, getHeight() - itemVerticalMargin); canvas.drawRoundRect(mRectF, r, r, mPaint); }
* 绘制选中Item的文字
当选中项移动时,刚移动到下一个Item时,颜色应该是选中的颜色。这里在原来文字之上再画选中Item的文字颜色,就有了被选中的效果。
/** * 画选中Item的文字 * @param canvas */ private void drawSelectedItemsText(Canvas canvas) { canvas.saveLayer(mStart, 0, mStart + mItemWidth, getHeight(), null, Canvas.ALL_SAVE_FLAG); mTextPaint.setColor(selectedItemTextColor); mTextPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); int begin = mStart/mItemWidth; int end = (begin + 2) < getCount()?begin+2:getCount(); for (int i = begin; i< end; i++){ int start = itemHorizontalMargin + i * mItemWidth; float x = start + (mItemWidth >> 1) - mTextPaint.measureText(getName(i))/2; float y = (getHeight() >> 1) - (mTextPaint.ascent() + mTextPaint.descent())/2; canvas.drawText(getName(i), x, y, mTextPaint); } canvas.restore(); }
手势分为三种,ACTION_DOWN、ACTION_MOVE、ACTION_UP,对应动作就是按下,滑动,按起。
当按下时确定按下位置,是在当前Item,则不做处理,当按下位置为其它Item位置,就滑动到其它Item位置。
当手势滑动时,计算相对滑动值,通过改变mStart
,改变选中项的位置。
当手势按起时,根据按下位置、速度和方向,判断是否可用移动到下一个Item。
@Override public boolean onTouchEvent(MotionEvent event) { if(!isEnabled() || !isInTouchMode() || getCount() == 0) return false; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); int action = event.getActionMasked(); if(action == MotionEvent.ACTION_DOWN){ x = event.getX(); onClickDownPosition = -1; final float y = event.getY(); if(isItemInside(x, y)){ return scrollSelectEnabled; }else if(isItemOutside(x, y)){ if(!mScroller.isFinished()){ mScroller.abortAnimation(); } onClickDownPosition = (int) ((x - itemHorizontalMargin)/ mItemWidth); startScroll(positionStart(x)); return true; } return false; }else if(action == MotionEvent.ACTION_MOVE){ if(!mScroller.isFinished() || !scrollSelectEnabled){ return true; } float dx = event.getX() - x; if(Math.abs(dx) > MIN_MOVE_X){ mStart = (int) (mStart + dx); mStart = Math.min(Math.max(mStart, itemHorizontalMargin), mEnd); postInvalidate(); x = event.getX(); } return true; }else if(action == MotionEvent.ACTION_UP){ int newSelectedItem; float offset = (mStart - itemHorizontalMargin)%mItemWidth; float itemStartPosition = (mStart - itemHorizontalMargin) * 1.0f/ mItemWidth; if(!mScroller.isFinished() && onClickDownPosition != -1){ newSelectedItem = onClickDownPosition; }else{ if(offset == 0f){ newSelectedItem = (int)itemStartPosition; }else { VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(VELOCITY_UNITS, mMaximumFlingVelocity); int initialVelocity = (int) velocityTracker.getXVelocity(); float itemRate = offset/mItemWidth; if (isXVelocityCanMoveNextItem(initialVelocity, itemRate)){ newSelectedItem = initialVelocity > 0?(int)itemStartPosition+1:(int)itemStartPosition; }else { newSelectedItem = Math.round(itemStartPosition); } newSelectedItem = Math.max(Math.min(newSelectedItem, getCount() - 1), 0); startScroll(getXByPosition(newSelectedItem)); } } onStateChange(newSelectedItem); mVelocityTracker = null; onClickDownPosition = -1; return true; } return super.onTouchEvent(event); }
当手机屏幕方向转换或者内存不足等情况下, 视图会重新加载,这样就会导致状态丢失。使用onSaveInstanceState
和onRestoreInstanceState
方法保存并恢复状态。
@Override public Parcelable onSaveInstanceState() { Parcelable parcelable = super.onSaveInstanceState(); SelectedItemState pullToLoadState = new SelectedItemState(parcelable); pullToLoadState.setSelectedItem(selectedItem); return pullToLoadState; } @Override public void onRestoreInstanceState(Parcelable state) { if(!(state instanceof SelectedItemState)) return; SelectedItemState pullToLoadState = ((SelectedItemState)state); super.onRestoreInstanceState(pullToLoadState.getSuperState()); selectedItem = pullToLoadState.getSelectedItem(); invalidate(); }
上述内容就是怎么在Android中利用View实现一个分段选择按钮,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。