在SeekBar和Fill之上绘制矩形

时间:2014-03-26 14:40:33

标签: android android-seekbar

我希望拥有SeekBar的功能,但是将线条(它是垂直的)自定义为一个矩形,每个区域最多我填充颜色。这是我扩展SeekBar的课程:

public class VerticalSeekBar extends SeekBar {

    private static final int NUMBER_OF_MINUTES = 120;
    private Paint mPaint = new Paint();

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMax(NUMBER_OF_MINUTES - 1);
    }

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    protected void onDraw(Canvas canvas) {
        canvas.rotate(90);
        canvas.translate(0, -getWidth());

        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                int i=0;
                i=getMax() - (int) (getMax() * event.getY() / getHeight());
                setProgress(getMax()-i);
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }

}

我想要一条粗的垂直线(矩形),我可以为120 max I的每个段填充颜色。这是一张图片:

enter image description here

我目前只有一个基本的垂直搜索栏,拇指作为滑块,它对应于列表视图中的位置。我需要seekBar,它与listView配对,并且取决于滑块的位置,我显示listview的那部分。

1 个答案:

答案 0 :(得分:0)

我想出了我需要做的事情。我的目标是使seekBar具有特定的宽度(或者它的高度是水平的seekBar转向侧面)。我需要progressDrawable区域小于为seekBar本身分配的大小。我还需要找到一种方法,绘制填充适当的空间,并在确定尺寸后应用渐变。这是我创建的代码片段,用于完成我需要的代码:

mVerticalSeekBar = (VerticalSeekBar) getView().findViewById(R.id.seekBar1);

LayerDrawable layers = setDrawablesWithGradientAndPadding();

mVerticalSeekBar.setProgressDrawable(layers);

protected LayerDrawable setDrawablesWithGradientAndPadding() {
        Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);
        ClipDrawable clipDrawable = new ClipDrawable(transparentDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
        GradientDrawable gradientDrawable = new GradientDrawable(Orientation.LEFT_RIGHT, getColors(jsonResults));
        /**
         * The padding can be confusing, applying to top and bottom, because it is actually applying to a horizontal
         * seekBar which I then flip in the onDraw() method in VerticalSeekBar.java
         */
        InsetDrawable insetDrawable = new InsetDrawable(gradientDrawable, 0, 40, 0, 40);

        LayerDrawable layers = new LayerDrawable(new Drawable[] { insetDrawable, clipDrawable });
        return layers;
    }

以下是结果的屏幕截图。

enter image description here