onMeasure和childview.layout

public class CustomViewGroup extends ViewGroup{

	public CustomViewGroup(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub

	    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        /**
         * 依据specMode的值,如果是AT_MOST,specSize 代表的是最大可获得的空间;如果是EXACTLY,specSize 代表的是精确的尺寸;如果是UNSPECIFIED,对于控件尺寸来说,没有任何参考意义。 
         */
        if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY)
        {
            throw new IllegalStateException("ApplicationsStackLayout can only be used with "
                    + "measure spec mode=EXACTLY");
        }
	    measureChildren(widthMeasureSpec, heightMeasureSpec);     

	    setMeasuredDimension(widthSize, heightSize);  
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		int mTotalHeight = 0;  

	       // 遍历所有子视图     
	    int childCount = getChildCount();  
	    for (int i = 0; i < childCount; i++) {  
	        View childView = getChildAt(i);  
	        
	        // 获取在onMeasure中计算的视图尺寸  
	        int measureHeight = childView.getMeasuredHeight();  
	        int measuredWidth = childView.getMeasuredWidth();  
	        if(i==1){
	        	childView.layout(50, mTotalHeight, measuredWidth+50, mTotalHeight + measureHeight);
	        }else
	        childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight);  

	        mTotalHeight += measureHeight;  


	    }  
	}

	
}


使用自定义的ViewGroup

<CustomViewGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff">
        <TextView android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="fasdjflsadjlf"
            android:background="#555555"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="fasdjflsadjlf"
            android:background="#999999"/>
    </CustomViewGroup>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值