Skip to content

Instantly share code, notes, and snippets.

@Lackofa7742
Last active September 19, 2018 10:50
Show Gist options
  • Save Lackofa7742/4108babd3da4382113e1e862dc0c7597 to your computer and use it in GitHub Desktop.
Save Lackofa7742/4108babd3da4382113e1e862dc0c7597 to your computer and use it in GitHub Desktop.
ViewPager for Android in Kotlin that respects wrap_content
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.View
/**
* Created by Magdiel Lorenzo on 5/20/17.
*/
class WrapContentViewPager : ViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attributes: AttributeSet) : super(context, attributes)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
/* Determine the height of the largest child and
* use that height as the height of the ViewPager
*/
for (i in 0..childCount - 1) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) {
height = h
}
}
val heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, heightSpec)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment