Search code examples
androidandroid-viewandroid-drawable

Call requires API level 29 (current min is 21): android.graphics.drawable.GradientDrawable#setPadding


Everytime i want to make this view below, i make a drawable resource and apply it to a view. enter image description here

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="-1dp"
        android:bottom="-1dp">
        <shape android:shape="rectangle">
            <stroke android:color="#d7d7d7" android:width="@dimen/px01" />
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

Now, I'm trying to make a code which applies border line programmatically.
The border line will be only shown top/right of the line and so on from time to time.
enter image description here

So, I decided to use the GradientDrawable#setPadding().

fun makeRectangleGradientDrawable(
    left: Int = 0,
    top: Int = 0,
    right: Int = 0,
    bottom: Int = 0,
    shape: Int = GradientDrawable.RECTANGLE,
    strokeWidth: Int = 1,
    strokeColor: Int,
    backgroundColor: Int
): GradientDrawable {
    return GradientDrawable().apply {
        this.setPadding(left, top, right, bottom) // Call requires API level 29 (current min is 21): android.graphics.drawable.GradientDrawable#setPadding
        this.shape = shape
        setStroke(strokeWidth, strokeColor)
    }
}

But my app supports API21(Lollipop) now and i can't use it. How can i make it by using GradientDrawable()? Or could you tell me a way to make it?


Solution

  • I think that the best option would be to wrap your gradient drawable in LayerList drawable and add some insets pixels to the edges.

    fun makeRectangleGradientDrawable(
        left: Int = 0,
        top: Int = 0,
        right: Int = 0,
        bottom: Int = 0,
        shape: Int = GradientDrawable.RECTANGLE,
        strokeWidth: Int = 1,
        strokeColor: Int,
        backgroundColor: Int
    ): Drawable {
        val border = GradientDrawable()
        border.setStroke(1, strokeColor)
        border.shape = GradientDrawable.RECTANGLE
        val layers = arrayOf<Drawable>(border)
        val layerDrawable = LayerDrawable(layers)
        layerDrawable.setLayerInset(0, left, top, right, bottom)
        return layerDrawable
    }