最近在做項(xiàng)目的時(shí)候使用了TabLayout+ViewPager 的組合來(lái)實(shí)現(xiàn)Tab頁(yè)切換的效果捅厂。不得不說(shuō)這個(gè)組合對(duì)項(xiàng)目開(kāi)發(fā)真的是提供了太大的便利贯卦,但有時(shí)也會(huì)有一些小尷尬。
問(wèn)題現(xiàn)象還原:我在Viewpager中放入了多個(gè)Fragment焙贷,當(dāng)ScrollView的內(nèi)容很多撵割,多到一個(gè)屏幕盛不了的時(shí)候(在我的項(xiàng)目中是有一個(gè)富文本區(qū)域,有時(shí)文本多到一頁(yè)盛不下)辙芍,下拉ScrollView到最后啡彬,發(fā)現(xiàn)ViewPager的內(nèi)容沒(méi)有顯示!沸手!
調(diào)試過(guò)程:
- 當(dāng)我把ViewPager的高度寫(xiě)成match_parent或者wrap_content時(shí)外遇,ViewPager無(wú)法顯示。當(dāng)我把ViewPager寫(xiě)死高度時(shí)契吉,F(xiàn)ragment正常顯示,但是我需要的是自適應(yīng)高度诡渴。
- 我發(fā)現(xiàn)在相同的頁(yè)面捐晶,如果富文本內(nèi)容不多菲语,F(xiàn)ragment正常顯示
- 我打了很多斷點(diǎn),發(fā)現(xiàn)一個(gè)問(wèn)題惑灵,當(dāng)初始化了Tablayout和ViewPager但是還未顯示ScollView中的富文本時(shí)候山上,F(xiàn)ragment是顯示了的,但是當(dāng)富文本顯示之后英支,Boom~Fragment消失了佩憾。
解決方案
自定義一個(gè)ViewPager,重寫(xiě)onMeasure方法干花。
class ScrollViewPager : ViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) height = h
}
val mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, mHeightMeasureSpec)
}
}
在布局文件中使用:
<com.peng.administrator.exchangeonlineplatform.view.custom.ScrollViewPager
android:id="@+id/viewPager_tuwen_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.peng.administrator.exchangeonlineplatform.view.custom.ScrollViewPager>
能解決你的問(wèn)題嗎妄帘?