Skip to content

Instantly share code, notes, and snippets.

@hector6872
Created May 9, 2018 16:21
Show Gist options
  • Save hector6872/9671cb91bcd0954cd32900aa1100e23f to your computer and use it in GitHub Desktop.
Save hector6872/9671cb91bcd0954cd32900aa1100e23f to your computer and use it in GitHub Desktop.
AspectRatioCardView Android - Kotlin
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)
)
}
}
<?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