view系列疑惑之你熟悉的LayoutParams

首先說下layoutParams,我們也很了解,顧名思義就是布局參數(shù),比如在布局文件中l(wèi)ayout_width和layout_height,那這兩個參數(shù)是view本身的屬性么?為啥我們編寫自定義viewGoup時通常要寫

public LayoutParams generateLayoutParams(AttributeSet attrs) { 
return new MarginLayoutParams(getContext(), attrs); 
} 
} 

其實呢,它是viewGroup的一個內(nèi)部類,我們簡單來分析下它:

public LayoutParams(Context c, AttributeSet attrs) {
          TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
          setBaseAttributes(a,
                  R.styleable.ViewGroup_Layout_layout_width,
                  R.styleable.ViewGroup_Layout_layout_height);
          a.recycle();
      }

      /**
       * Creates a new set of layout parameters with the specified width
       * and height.
       *
       * @param width the width, either {@link #WRAP_CONTENT},
       *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
       *        API Level 8), or a fixed size in pixels
       * @param height the height, either {@link #WRAP_CONTENT},
       *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
       *        API Level 8), or a fixed size in pixels
       */
      public LayoutParams(int width, int height) {
          this.width = width;
          this.height = height;
      }

      /**
       * Copy constructor. Clones the width and height values of the source.
       *
       * @param source The layout params to copy from.
       */
      public LayoutParams(LayoutParams source) {
          this.width = source.width;
          this.height = source.height;
      }

我們看下誰調(diào)用了它的第一個構(gòu)造,很明顯是viewGroup里的一個
generateLayoutParams()方法,熟悉view.inflate的人知道,原來在
XmlPullParser解析以后

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

很顯然當這個你寫的這個自定義view被xml的布局文件被解析的時候
其viewGroup在addview前都會調(diào)用generateLayoutParams而這個方法的參數(shù)就是這個view在xml的屬性,所以如果我們這個方法不重寫,那子這個viewGroup里的子view就不支持margin了,因為他根本取不到這幾個layout_marginleft,layout_marginRight,等值
那在看看addview里面

if (child == null) {
           throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
       }
       LayoutParams params = child.getLayoutParams();
       if (params == null) {
           params = generateDefaultLayoutParams();
           if (params == null) {
               throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
           }
       }
       addView(child, index, params);

當我們在代碼里父view add子view時,子view沒有LayoutParams,可以看到系統(tǒng)會給默認的generateDefaultLayoutParams(),當然了,我們寫自定義view最好也要復寫這個方法,萬一比人是在代碼里添加的子view,怎么不能設(shè)置margin了,最后,我們在addviewInner里
看到了

private void addViewInner(View child, int index, LayoutParams params,
            boolean preventRequestLayout) {

        if (mTransition != null) {
            // Don't prevent other add transitions from completing, but cancel remove
            // transitions to let them complete the process before we add to the container
            mTransition.cancel(LayoutTransition.DISAPPEARING);
        }

        if (child.getParent() != null) {
            throw new IllegalStateException("The specified child already has a parent. " +
                    "You must call removeView() on the child's parent first.");
        }

        if (mTransition != null) {
            mTransition.addChild(this, child);
        }

        if (!checkLayoutParams(params)) {
            params = generateLayoutParams(params);
        }

checkLayoutParams和generateLayoutParams(params)這是啥意思呢
其實這是檢查你的params是否是正確的,當然子類可以復寫這兩個條件,一般來說,checkLayoutParamsl里條件是p!=null而且不是你的自定義viewGroup的定義的layoutParams的子類,這樣父view可以幫你生成一個符合其viewGroup的params,具體例子請看LinearLayout

  /**
    xml生成
     */
@Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LinearLayout.LayoutParams(getContext(), attrs);
    }

    /**
    生成默認的
     */
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        if (mOrientation == HORIZONTAL) {
            return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        } else if (mOrientation == VERTICAL) {
            return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }
        return null;
    }
  /**
    addview時params搞錯了,糾錯
     */
    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
        if (sPreserveMarginParamsInLayoutParamConversion) {
            if (lp instanceof LayoutParams) {
                return new LayoutParams((LayoutParams) lp);
            } else if (lp instanceof MarginLayoutParams) {
                return new LayoutParams((MarginLayoutParams) lp);
            }
        }
        return new LayoutParams(lp);
    }


    // Override to allow type-checking of LayoutParams.
   //查看params類型是否正確
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LinearLayout.LayoutParams;
    }

對于layoutParams大致的都分析完了,沒看懂的我相信看了LinearLayout的例子也明白了吧
ps:其實generateLayoutParams方法的作用其實就是定義你的控件下所有子控件所使用的layoutParams類 通過這種形式使你的控件可以按自己想要的方式和屬性來操作它的子view,這也是為何view.inflate中的根view設(shè)置padding有效,而設(shè)置margin和width,height無效的原因,并不是網(wǎng)上大多數(shù)人說的去掉最外面一層,本質(zhì)還是有差別的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容