Skip to content

Instantly share code, notes, and snippets.

@mzgreen
Last active February 13, 2021 15:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzgreen/1e35d7cf7c902988884650b6da72d6dc to your computer and use it in GitHub Desktop.
Save mzgreen/1e35d7cf7c902988884650b6da72d6dc to your computer and use it in GitHub Desktop.
A ConstraintHelper implementation that has additional layout params: screenHeight_percent and screenWidth_percent which allow to make referenced views height and width to be equal to screenHeight(or screenWidth)*some_percent_value. Where some_percent_value is a value between 0.0 and 1.0.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SizeHelper">
<attr name="screenHeight_percent" format="float"/>
<attr name="screenWidth_percent" format="float"/>
</declare-styleable>
</resources>
class SizeHelper @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintHelper(context, attrs, defStyleAttr) {
private val screenHeight: Int = resources.displayMetrics.heightPixels
private val screenWidth: Int = resources.displayMetrics.widthPixels
private var layoutConstraintScreenHeightPercent = UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT
private var layoutConstraintScreenWidthPercent = UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT
init {
attrs?.let { readAttributes(it) }
}
private fun readAttributes(attrs: AttributeSet) {
val styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.SizeHelper)
layoutConstraintScreenHeightPercent = styledAttrs.getFloat(
R.styleable.SizeHelper_screenHeight_percent, UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT)
layoutConstraintScreenWidthPercent = styledAttrs.getFloat(
R.styleable.SizeHelper_screenWidth_percent, UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT)
styledAttrs.recycle()
}
override fun updatePostMeasure(container: ConstraintLayout) {
for (i in 0 until this.mCount) {
val id = this.mIds[i]
val child = container.getViewById(id)
val widget = container.getViewWidget(child)
if (layoutConstraintScreenHeightPercent != UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT) {
// layout_constraintScreenHeight_percent is set so override current child height
val newHeight = screenHeight * layoutConstraintScreenHeightPercent
widget.height = newHeight.toInt()
}
if (layoutConstraintScreenWidthPercent != UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT) {
// layout_constraintScreenWidth_percent is set so override current child width
val newWidth = screenWidth * layoutConstraintScreenWidthPercent
widget.width = newWidth.toInt()
}
}
}
companion object {
const val UNSPECIFIED_CONSTRAINT_SCREEN_PERCENT = -1.0f
}
}
@mochadwi
Copy link

really thanks for this!!! @mzgreen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment