4.关于View的绘制 (中):layout

1.Layout过程

  1. View的layout
    view的layout方法用来确定view本身的位置
public void layout(int l, int t, int r, int b) {
	...
}
  • 先通过setFrame来设定4个定点位置,view在父容器中位置就确定来
  • layout内部调用onLayout, 用于父容器确定子元素位置(View未实现onLayout, 需要自己实现)
/**
     * Called from layout when this view should
     * assign a size and position to each of its children.
     *
     * Derived classes with children should override
     * this method and call layout on each of
     * their children.
     * @param changed This is a new size or position for this view
     * @param left Left position, relative to parent
     * @param top Top position, relative to parent
     * @param right Right position, relative to parent
     * @param bottom Bottom position, relative to parent
     */
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }
  1. ViewGroup的layout
    确定所有子元素的位置
  • viewGroup的layout为final方法,不能覆写,其实现为View.layout
    @Override
    public final void layout(int l, int t, int r, int b) {
        if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
            if (mTransition != null) {
                mTransition.layoutChange(this);
            }
            super.layout(l, t, r, b);
        } else {
            // record the fact that we noop'd it; request layout when transition finishes
            mLayoutCalledWhileSuppressed = true;
        }
    }
  • ViewGroup.onLayout为抽象方法,需要覆写
    @Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

3.总结

  • View与ViewGroup的layout实为一套流程,onLayout都是实现,需要根据具体的布局来实现,可参考TextView, LinearLayout的实现。
  • measure过程确定测量宽高,layout过程确定4定点位置即最终宽高,有何不同?
    measure, getMeasureWidth
    layout, getWidth = mRight - mLeft
    二者时序不同,值是相等的, measure先,layout后;
    若覆写View.layout ,修改4点的参数,则会导致二者不同
发布了37 篇原创文章 · 获赞 0 · 访问量 544

猜你喜欢

转载自blog.csdn.net/qq_37514242/article/details/104445619