7

I have a ShapeDrawable:

final ShapeDrawable drawable = new ShapeDrawable(shape);
drawable.getPaint().setStyle(Paint.Style.FILL);
drawable.getPaint().setColor(0xFFffffff);

I want to set border(stroke) color and width for this drawable.

I try setStyle(Paint.Style.FILL_AND_STROKE) but it set background and border with same color

Hossain Khademian
  • 1,616
  • 3
  • 19
  • 29

2 Answers2

3

Use

drawable.getPaint().setStyle(Paint.Style.STROKE);
drawable.getPaint().setStrokeWidth(2); // in pixel
Richard Chang
  • 281
  • 2
  • 10
  • And what about the missing border color? This answer should never got upvoted because it doesn't answer the main question. – d.aemon Jun 24 '20 at 09:51
3

If you have a view such as a TextView where you need to set the background and border you can do it like this Kotlin code:

val view = findViewById(R.id.miTextView) as TextView
val borderColor : Int = Color.GRAY,
val backgroundColor : Int = Color.GRAY,
val borderWidth : Float = 5F,
val borderRadius : Float = 15F
val borderShape = ShapeDrawable().apply {
    shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
    paint.color = borderColor
    paint.style = Paint.Style.STROKE;
    paint.strokeWidth = borderWidth;
}
val backgroundShape = ShapeDrawable().apply {
    shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
    paint.color = backgroundColor
    paint.style = Paint.Style.FILL_AND_STROKE;
}
val composite = LayerDrawable(arrayOf<Drawable>(backgroundShape, borderShape))
view.background = composite