Last active
December 9, 2019 20:20
-
-
Save L-Briand/1d7721ac80e11b23a345ca413c8bf435 to your computer and use it in GitHub Desktop.
A simple class to extend when creating a custom view that has some width and height requirement.
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.content.Context | |
import android.graphics.RectF | |
import android.util.AttributeSet | |
import android.view.View | |
import androidx.annotation.Nullable | |
import kotlin.math.min | |
abstract class SizedView @JvmOverloads constructor( | |
context: Context, | |
@Nullable attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0, | |
defStyleRes: Int = 0 | |
) : View(context, attrs, defStyleAttr, defStyleRes) { | |
abstract val desiredWidth: Float | |
abstract val desiredHeight: Float | |
val paddingBox: RectF = RectF() | |
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { | |
val desiredWidth = desiredWidth.toInt() + paddingStart + paddingEnd | |
val desiredHeight = desiredHeight.toInt() + paddingTop + paddingBottom | |
val widthMode = MeasureSpec.getMode(widthMeasureSpec) | |
val widthSize = MeasureSpec.getSize(widthMeasureSpec) | |
val heightMode = MeasureSpec.getMode(heightMeasureSpec) | |
val heightSize = MeasureSpec.getSize(heightMeasureSpec) | |
val width: Int = when (widthMode) { | |
MeasureSpec.EXACTLY -> widthSize | |
MeasureSpec.AT_MOST -> min(desiredWidth, widthSize) | |
else -> desiredWidth | |
} | |
val height: Int = when (heightMode) { | |
MeasureSpec.EXACTLY -> heightSize | |
MeasureSpec.AT_MOST -> min(desiredHeight, heightSize) | |
else -> desiredHeight | |
} | |
setMeasuredDimension(width, height) | |
} | |
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { | |
super.onSizeChanged(w, h, oldw, oldh) | |
paddingBox.set( | |
paddingStart.toFloat(), | |
paddingTop.toFloat(), | |
width.toFloat() - paddingRight.toFloat(), | |
height.toFloat() - paddingBottom.toFloat() | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment