0

Aim: Stroke only the top and bottom.

What I've tried:

Below is a copy of my XML. I've tried following the solution in This Stack Overflow Answer. But my problem is that the doesn't let me choose the options of cutting off the left and right by 1dp as per the solution.

Any ideas?

Code:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape >
            <gradient
                    android:startColor="@color/secondaryButtonStartColorSelected"
                    android:endColor="@color/secondaryButtonEndColorSelected"
                    android:angle="270" />
            <stroke
                    android:width="@dimen/secondary_button_border_size"
                    android:color="@color/secondaryButtonBorderColorSelected" />

        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                    android:startColor="@color/secondaryButtonStartColorSelected"
                    android:endColor="@color/secondaryButtonEndColorSelected"
                    android:angle="270" />
            <stroke
                    android:width="@dimen/secondary_button_border_size"
                    android:color="@color/secondaryButtonBorderColorSelected"/>

        </shape>
    </item>

</selector>
Community
  • 1
  • 1
SalicBlu3
  • 1,874
  • 2
  • 19
  • 32

1 Answers1

0

You could create a custom Drawable to handle this for you, but you'd have to set it in code vs XML. Here's a quick and dirty version:

public class HorizontalStrokeDrawable extends Drawable {
    private Paint mPaint = new Paint();
    private int mStrokeWidth;

    public HorizontalStrokeDrawable (int strokeColor, int strokeWidth) {
        mPaint.setColor(strokeColor);
        mStrokeWidth = strokeWidth;
    }

    @Override
    public void draw (Canvas canvas) {
        Rect bounds = getBounds();
        canvas.drawRect(0, 0, bounds.right, mStrokeWidth, mPaint);
        canvas.drawRect(0, bounds.bottom - mStrokeWidth, bounds.right, bounds.bottom, mPaint);
    }

    @Override
    public void setAlpha (int alpha) {
        mPaint.setAlpha(alpha);
        invalidateSelf();
    }

    @Override
    public void setColorFilter (ColorFilter cf) {
        mPaint.setColorFilter(cf);
        invalidateSelf();
    }

    @Override
    public int getOpacity () {
        return PixelFormat.TRANSLUCENT;
    }
}

Now you can just set it wherever you need it:

view.setBackgroundDrawable(new HorizontalStrokeDrawable(myColor, myStrokeWidth));
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274