带数字进度的seekbar

最近做项目有个需求是要使用seekbar的,但是原生的seekbar又不满足要求,只能自己动手操作了。  
首先先交代下需求:在seekbar滑动的过程中在其上方动态的显示当前的进度。

思路:  
1、在seekbar上方动态的添加一个textview   
2、在seekbar滑动监听中修改textview的位置 
 
就是这么简单,那么实现起来怎么样呢?   
为了能够动态的添加textview所以新建了而一个TextMoveLayout类并且重写了onMessure方法使其能够wrap_content,代码如下:

    public class TextMoveLayout extends ViewGroup {

        public TextMoveLayout(Context context) {
            super(context);
        }
    
        public TextMoveLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        public TextMoveLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
    
        }
    
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            int desiredWidth = 100;
            int desiredHeight = 100;
    
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    
            int width;
            int height;
    
            if (widthMode == MeasureSpec.EXACTLY) {
                width = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(desiredWidth, widthSize);
            } else {
                width = desiredWidth;
            }
    
            if (heightMode == MeasureSpec.EXACTLY) { 
                height = heightSize;
            } else if (heightMode == MeasureSpec.AT_MOST) { 
                height = Math.min(desiredHeight, heightSize);
            } else { 
                height = desiredHeight;
            }
            setMeasuredDimension(width, height);
        }
    }


接下来就是要确定textview的位置了,也就是当前seekbar的thume的位置:   
 

  坐标的确定:
	 seekbar的背景长度*seekbar当前进度/seekbar的max - textview的长度/2 + textview的margin值

 

 

 

 

 


代码表示如下:

    //测量textview的文字宽度
    float measureText = mPaint.measureText(moveText.getText().toString().trim());
    //获取seekbar背景的bounds 通过bounds获取width
    Rect bounds = mSeekbar.getProgressDrawable().getBounds();
    int xFloat = (int) (bounds.width() * mSeekbar.getProgress() / mSeekbar.getMax() - measureText / 2 + DensityUtil.px2dip(MainActivity.this, mLeftMargin));


以上代码是实现需求的核心代码。

获取Xml中配置的margin值

    View childAt = mParentView.getChildAt(0);
    ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) 
							childAt.getLayoutParams();
    mLeftMargin = marginLayoutParams.leftMargin;

 

预览图如下:

带数字进度的seekbar_第1张图片带数字进度的seekbar_第2张图片


最后附上源码下载地址:

http://download.csdn.net/detail/siyemuzi/9596329
 

扫描下方二维码关注公众号,及时获取文章推送



你可能感兴趣的:(Android)