Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Mariovc
Last active February 23, 2022 12:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Mariovc/48fc96da662b08e8e02cd36e08380390 to your computer and use it in GitHub Desktop.
Save Mariovc/48fc96da662b08e8e02cd36e08380390 to your computer and use it in GitHub Desktop.
ScrollView extended to use a max height together with wrap_content
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ScrollViewWithMaxHeight">
<attr name="android:maxHeight" />
</declare-styleable>
</resources>
import android.content.Context
import android.util.AttributeSet
import android.widget.ScrollView
import timber.log.Timber
class ScrollViewWithMaxHeight @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
companion object {
var WITHOUT_MAX_HEIGHT_VALUE = -1
}
private var maxHeight = WITHOUT_MAX_HEIGHT_VALUE
init {
val a = context.obtainStyledAttributes(
attrs, R.styleable.ScrollViewWithMaxHeight,
defStyleAttr, 0
)
try {
maxHeight = a.getDimension(
R.styleable.ScrollViewWithMaxHeight_android_maxHeight,
WITHOUT_MAX_HEIGHT_VALUE.toFloat()
).toInt()
} finally {
a.recycle()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightMeasure = heightMeasureSpec
try {
var heightSize = MeasureSpec.getSize(heightMeasureSpec)
if (maxHeight != WITHOUT_MAX_HEIGHT_VALUE) {
heightSize = maxHeight
heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST)
} else {
heightMeasure = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.UNSPECIFIED)
}
layoutParams.height = heightSize
} catch (e: Exception) {
Timber.e(e, "Error forcing height")
} finally {
super.onMeasure(widthMeasureSpec, heightMeasure)
}
}
fun setMaxHeight(maxHeight: Int) {
this.maxHeight = maxHeight
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment