Created
May 9, 2018 16:21
-
-
Save hector6872/9671cb91bcd0954cd32900aa1100e23f to your computer and use it in GitHub Desktop.
AspectRatioCardView Android - Kotlin
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
class AspectRatioCardView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0 | |
) : CardView(context, attrs, defStyleAttr) { | |
private var ratio = 1.0f | |
init { | |
attrs?.let { | |
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AspectRatioCardView) | |
ratio = typedArray.getFloat(R.styleable.AspectRatioCardView_arcv_ratio, 1.0f) | |
typedArray.recycle() | |
} | |
} | |
override fun onMeasure( | |
widthMeasureSpec: Int, | |
heightMeasureSpec: Int | |
) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec) | |
val widthWithoutPadding = measuredWidth - paddingLeft - paddingRight | |
val maxHeight = (widthWithoutPadding * ratio).toInt() | |
val width = widthWithoutPadding + paddingLeft + paddingRight | |
val height = maxHeight + paddingTop + paddingBottom | |
super.onMeasure( | |
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), | |
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY) | |
) | |
} | |
} |
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
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="AspectRatioCardView"> | |
<attr format="float" name="arcv_ratio"/> | |
</declare-styleable> | |
</resources> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment