多色自定义搜索栏

时间:2018-04-27 12:00:55

标签: java android android-layout

我正在尝试使用多色在android中创建自定义搜索栏。我试过下面的代码

customseekbar.java

int proBarWidth = getWidth();
int proBarHeight = getHeight();
int thumboffset = getThumbOffset();
int lastproX = 0;
int proItemWidth, proItemRight;
for (int i = 0; i < mproItemsList.size(); i++) {
proItem proItem = mproItemsList.get(i);
Paint proPaint = new Paint();
proPaint.setColor(getResources().getColor(proItem.color));

proItemWidth = (int) (proItem.proItemPercentage
        * proBarWidth / 100);

proItemRight = lastproX + proItemWidth;

// for last item give right of the pro item to width of the
// pro bar
if (i == mproItemsList.size() - 1
        && proItemRight != proBarWidth) {
    proItemRight = proBarWidth;
}
Rect proRect = new Rect();
proRect.set(lastproX, thumboffset / 2, proItemRight,
        proBarHeight - thumboffset / 2);
canvas.drawRect(proRect, proPaint);
lastproX = proItemRight;
}
super.onDraw(canvas);

查看

<mypackage.customseekbar
android:id="@+id/customseekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:progressDrawable="@android:color/transparent"
android:thumb="@drawable/seek_thumb_normal"
android:thumbOffset="12dp" />

我在MainMenuActivity中使用了这种方法。它给我的结果如下。我提到了这个链接https://azzits.wordpress.com/2013/11/17/customseekbar/ enter image description here

但是我期待像enter image description here

下面的东西

有没有办法绘制这条垂直缺口线?我该如何绘制这条垂直线?

1 个答案:

答案 0 :(得分:3)

Progress bar with divider是@Nilesh Rathod提到的好地方。您可以使用canvas.drawRoundRect();而不是使用canvas.drawRect();简短的例子:

for (int i = 0; i < NUM_SEGMENTS; i++) {
        float loLevel = i / (float) NUM_SEGMENTS;
        float hiLevel = (i + 1) / (float) NUM_SEGMENTS;
        if (loLevel <= level && level <= hiLevel) {
            float middle = mSegment.left + NUM_SEGMENTS * segmentWidth * (level - loLevel);
            canvas.drawRoundRect(mSegment.left, mSegment.top, middle, mSegment.bottom, mPaint);
            mPaint.setColor(mBackground);
            canvas.drawRoundRect(middle, mSegment.top, mSegment.right, mSegment.bottom, mPaint);
        } else {
            canvas.drawRoundRect(mSegment, mPaint);
        }
        mSegment.offset(mSegment.width() + gapWidth, 0);
    }

我将上述代码完全归功于上述链接的创建者,并且不会将其中的任何内容声明为我的,因为我只是说明了为达到预期效果而应该做出的改变。如果您遇到其他问题,请告诉我。