View.inflate、LayoutInflator.inflate

核心源码:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    final Context inflaterContext = mContext;
    final AttributeSet attrs = Xml.asAttributeSet(parser);
    
    // 默认返回结果为传入的根布局
    View result = root;
  
    // 通过 createViewFromTag() 方法找到传入的 layoutId 的根布局,并赋值给 temp
    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
    ViewGroup.LayoutParams params = null;
  
    // 如果传入的父布局不为空
    if (root != null) {
        // 为这个 root 生成一套合适的 LayoutParams
        params = root.generateLayoutParams(attrs);
        if (!attachToRoot) {
            // 如果没有 attachToRoot,那为根布局设置 layoutparams
            temp.setLayoutParams(params);
        }
    }

    // 如果传入的父布局不为空,且想要 attachToRoot
    if (root != null && attachToRoot) {
        // 那就将传入的布局以及 layoutparams 通过 addView 方法添加到父布局中 
        root.addView(temp, params);
    }

    // 如果传入的根布局为空,或者不想 attachToRoot,则返回要加载的 layoutId
    if (root == null || !attachToRoot) {
        result = temp;
    }
    return result;
}

总结:

 

 想详细了解,参考此篇文章

posted on 2021-06-30 13:48  汤姆猫8  阅读(58)  评论(0)    收藏  举报