标签:
Android开发中,常会遇到侧滑翻页的效果,android.support.v4.view.ViewPager让这种实现变得简单易用,但是通常使用时,都是让ViewPager的宽和高去match_parent,或者布局时制定了ViewPager的高度,所以一切正常。偶然的一次布局改变,着实一头雾水了半天。
场景:页面某个区域显示ViewPager用来翻页,但是ViewPager中的试图并不是设计期加上去的,所以希望ViewPager可以wrap_content自适应child的高度,布局设计好后,感觉一切良好,因为最常用的各种layout设置wrap_content都能很好的工作,ViewPager也是容器,所以认为理所当然运行正常。
真正的运行app后发现,始终无法显示我动态添加进去的child,跟踪代码也未发现异常。好吧,那我们改一下布局,设定ViewPager的高度为100dp,再次运行,靠,啥都能看见了!
这会大家应该明白了吧,ViewPager设定wrap_content无效,他不会根据child视图去计算自己的高度,网上找到了ViewPager的onMeasure的代码,如下:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, or internal size is always 0. // We depend on the container to specify the layout size of // our view. We can‘t really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. mInLayout = true; populate(); mInLayout = false; // Make sure all children have been properly measured. final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec); child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); } } }
既然知道了这个原因,那如果我们需要让他适应我们自己的高度呢(假如我们添加的视图都是一样的),那么我们就继承ViewPager,然后重写onMeasure
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for(int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); if(h > height) height = h; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/bdmh/article/details/48243081