重写ViewPager实现Scrollview嵌套ViewPager高度自适应

本文介绍了一种解决ScrollView嵌套ViewPager时高度自适应的问题,通过重写ViewPager的onMeasure方法来实现每个页面的高度能够根据内容自适应变化,避免了因内容高度不同导致的显示空白。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. public class MyViewPager extends ViewPager {  
  2.     public MyViewPager(Context context) {  
  3.         super(context);  
  4.     }  
  5.   
  6.     /** 
  7.      * Constructor 
  8.      * 
  9.      * @param context the context 
  10.      * @param attrs the attribute set 
  11.      */  
  12.     public MyViewPager(Context context, AttributeSet attrs) {  
  13.         super(context, attrs);  
  14.     }  
  15.   
  16.   
  17.     @Override  
  18.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  19.   
  20.         int height = 0;  
  21.         for(int i = 0; i < getChildCount(); i++) {  
  22.             View child = getChildAt(i);  
  23.             child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
  24.             int h = child.getMeasuredHeight();  
  25.             if(h > height) height = h;  
  26.         }  
  27.   
  28.         heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);  
  29.   
  30.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  31.     }  
  32.     /** 
  33.      * Determines the height of this view 
  34.      * 
  35.      * @param measureSpec A measureSpec packed into an int 
  36.      * @param view the base view with already measured height 
  37.      * 
  38.      * @return The height of the view, honoring constraints from measureSpec 
  39.      */  
  40.     private int measureHeight(int measureSpec, View view) {  
  41.         int result = 0;  
  42.         int specMode = MeasureSpec.getMode(measureSpec);  
  43.         int specSize = MeasureSpec.getSize(measureSpec);  
  44.   
  45.         if (specMode == MeasureSpec.EXACTLY) {  
  46.             result = specSize;  
  47.         } else {  
  48.             // set the height from the base view if available  
  49.             if (view != null) {  
  50.                 result = view.getMeasuredHeight();  
  51.             }  
  52.             if (specMode == MeasureSpec.AT_MOST) {  
  53.                 result = Math.min(result, specSize);  
  54.             }  
  55.         }  
  56.         return result;  
  57.     }  
  58.   
  59. }  

参照:http://blog.youkuaiyun.com/lzq520210/article/details/53197535
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值