Long Dao
Long Dao

Reputation: 1371

How to convert android:radius in xml to float value in Kotlin Android

I have a drawable background xml file as below, where I set the radius for the view to 40dp:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="@color/jungleGreen"/>
    <corners
        android:bottomLeftRadius="40dp"
        android:topLeftRadius="40dp"/>
</shape>

For few specific reasons I need to do the same thing programmatically in Kotlin Android. So I wrote a function as below to do it:

private fun setupGraphBackground(view: View) {
        val gradientDrawable = GradientDrawable()
        gradientDrawable.shape = GradientDrawable.RECTANGLE
        gradientDrawable.setColor(resources.getColor(R.color.jungleGreen))
        gradientDrawable.setStroke(0, null)
        gradientDrawable.cornerRadii = floatArrayOf(45f, 45f, 0f, 0f, 0f, 0f, 45f, 45f)
        view.background = gradientDrawable
    }

Basically, I found out that if I set value in my function to 45f, it will be likely as close as 40dp in the xml file.

My question is that, is there any rules to convert it to the the exactly correct number? Seems like there is no documentation anywhere.

Any help would be appreciated.

Thanks.

Upvotes: 1

Views: 795

Answers (1)

Aram Sheroyan
Aram Sheroyan

Reputation: 588

Any value that you set programmatically is treated as a pixel. You should actually convert the dp value that you want to pixels. You can use this method

fun dpToPx(context: Context, dp: Float): Float {
    return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

And use it like this

private fun setupGraphBackground(view: View) {
    val gradientDrawable = GradientDrawable()
    val rad = dpToPx(context, 40f)
    gradientDrawable.shape = GradientDrawable.RECTANGLE
    gradientDrawable.setColor(resources.getColor(R.color.jungleGreen))
    gradientDrawable.setStroke(0, null)
    gradientDrawable.cornerRadii = floatArrayOf(rad, rad, 0f, 0f, 0f, 0f, rad, rad)
    view.background = gradientDrawable
}

You can also create a UIUtils class and add this method inside a companion object so you can call it from anywhere you need.

Upvotes: 2

Related Questions