Last active
August 4, 2022 06:42
-
-
Save MohammadRezaAlizadeh000/b06709779ab74400528a86d62fc498e7 to your computer and use it in GitHub Desktop.
Instead of use xml file to create shape you can use this extension to create your drawable shape at run time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.drawable.GradientDrawable | |
import android.view.View | |
import androidx.core.content.ContextCompat | |
import androidx.core.content.res.ResourcesCompat | |
import androidx.fragment.app.Fragment | |
fun Fragment.createBackground( | |
color: Int, | |
corner: Int = 0, | |
corners: IntArray = intArrayOf(), | |
borderColor: Int = 0, | |
borderWidth: Int = 0 | |
) = GradientDrawable().apply { | |
setColor(ContextCompat.getColor(requireContext(), color)) | |
if (corners.isNotEmpty()) { | |
val newCorners = mutableListOf<Float>() | |
for (cor in corners.indices) { | |
if (corners[cor] != 0){ | |
newCorners.add(resources.getDimensionPixelSize(corners[cor]).toFloat()) | |
newCorners.add(resources.getDimensionPixelSize(corners[cor]).toFloat()) | |
} else{ | |
newCorners.add(0F) | |
newCorners.add(0F) | |
} | |
} | |
cornerRadii = newCorners.toFloatArray() | |
} else | |
cornerRadius = resources.getDimensionPixelSize(corner).toFloat() | |
if (borderWidth and borderColor != 0) | |
setStroke(borderWidth, borderColor) | |
} | |
fun View.createBackground( | |
color: Int, | |
corner: Int = 0, | |
corners: IntArray = intArrayOf(), | |
borderColor: Int = 0, | |
borderWidth: Int = 0 | |
) = GradientDrawable().apply { | |
setColor(ContextCompat.getColor(context, color)) | |
if (corners.isNotEmpty()) { | |
val newCorners = mutableListOf<Float>() | |
for (cor in corners.indices) { | |
if (corners[cor] != 0){ | |
newCorners.add(resources.getDimensionPixelSize(corners[cor]).toFloat()) | |
newCorners.add(resources.getDimensionPixelSize(corners[cor]).toFloat()) | |
} else{ | |
newCorners.add(0F) | |
newCorners.add(0F) | |
} | |
} | |
cornerRadii = newCorners.toFloatArray() | |
} else | |
cornerRadius = resources.getDimensionPixelSize(corner).toFloat() | |
if (borderWidth and borderColor != 0) | |
setStroke(borderWidth, borderColor) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment