gpt4 book ai didi

android - 具有不同项目高度和 WRAP_CONTENT 的 ViewPager2

转载 作者:行者123 更新时间:2023-12-04 23:35:54 25 4
gpt4 key购买 nike

有几篇文章介绍了如何让 ViewPager 处理以扩展 ViewPager 为中心的不同高度项目。自己修改其onMeasure支持这一点。
但是,鉴于 ViewPager2 被标记为最终类,扩展它不是我们可以做的事情。
有谁知道是否有办法解决这个问题?

例如。假设我有两种观点:
View 1 = 200dp
View 2 = 300dp
当 ViewPager2 (layout_height="wrap_content") 加载时——查看 View1,它的高度将为 200dp。
但是当我滚动到 View2 时,高度仍然是 200dp; View2 的最后 100dp 被截断。

最佳答案

解决办法是注册一个PageChangeCallback并调整 LayoutParamsViewPager2在要求 child 重新测量自己之后。

pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
val view = // ... get the view
view.post {
val wMeasureSpec = MeasureSpec.makeMeasureSpec(view.width, MeasureSpec.EXACTLY)
val hMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
view.measure(wMeasureSpec, hMeasureSpec)

if (pager.layoutParams.height != view.measuredHeight) {
// ParentViewGroup is, for example, LinearLayout
// ... or whatever the parent of the ViewPager2 is
pager.layoutParams = (pager.layoutParams as ParentViewGroup.LayoutParams)
.also { lp -> lp.height = view.measuredHeight }
}
}
}
})
或者,如果您的 View 的高度可能由于例如异步数据加载,然后使用全局布局监听器代替:
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
private val listener = ViewTreeObserver.OnGlobalLayoutListener {
val view = // ... get the view
updatePagerHeightForChild(view)
}

override fun onPageSelected(position: Int) {
super.onPageSelected(position)
val view = // ... get the view
// ... IMPORTANT: remove the global layout listener from other views
otherViews.forEach { it.viewTreeObserver.removeOnGlobalLayoutListener(layoutListener) }
view.viewTreeObserver.addOnGlobalLayoutListener(layoutListener)
}

private fun updatePagerHeightForChild(view: View) {
view.post {
val wMeasureSpec = MeasureSpec.makeMeasureSpec(view.width, MeasureSpec.EXACTLY)
val hMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
view.measure(wMeasureSpec, hMeasureSpec)

if (pager.layoutParams.height != view.measuredHeight) {
// ParentViewGroup is, for example, LinearLayout
// ... or whatever the parent of the ViewPager2 is
pager.layoutParams = (pager.layoutParams as ParentViewGroup.LayoutParams)
.also { lp -> lp.height = view.measuredHeight }
}
}
}
}
请参阅此处的讨论:
https://issuetracker.google.com/u/0/issues/143095219

关于android - 具有不同项目高度和 WRAP_CONTENT 的 ViewPager2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com