自定义 View:Layout 过程

1、作用
  1. 作用:计算 View 的位置。
2、Layout 过程
  1. View 的 Layout 过程:layout->onLayout(空实现)。
	View.java
	// 四个顶点位置,确定 view 的位置
    public void layout(int l, int t, int r, int b) {
       
        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;
        
		// 确定View的位置
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
		// 视图位置发生变化,重新确定所有子view在父view的位置。
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
        	// view 的 onLayout 空实现
            onLayout(changed, l, t, r, b);
			。。。
            }

    }

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }
  1. ViewGroup 的 Layout 过程:layout->onLayout(重写)->遍历子view位置。
	ViewGroup.java
	
	// 抽象方法,必须重写。
    @Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

	/**
	 * 重写步骤
	 */
	protected void onLayout(boolean changed,
            int l, int t, int r, int b){
		// 1、遍历子view
		for(int i = 0;i<getChildCount();i++){
			View child = getChildAt(i);
			// 2、计算子view的位置
			int left,top,right,bottom;
			...
			// 3、确定子view的位置
			child.layout(left, top, right, bottom);
		}
	}
  1. 获取view的宽高
	View.java
	
	// 获取view测量后宽高
    public final int getMeasuredWidth() {
        return mMeasuredWidth & MEASURED_SIZE_MASK;
    }
    public final int getMeasuredHeight() {
        return mMeasuredHeight & MEASURED_SIZE_MASK;
    }
	// 获取view最终宽高
    public final int getWidth() {
        return mRight - mLeft;
    }
    public final int getHeight() {
        return mBottom - mTop;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值