Android Inflate 的使用

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/ContainsK/article/details/72868562

在使用View.Inflate(context,resid,root)創建recyclerview item佈局時,根佈局的margin,pading都沒有起作用.

看了它其中的源碼使用的是LayoutInflater.from().inflate(),層層跟進發現其中有一段邏輯:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
		.......省略代碼
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                ViewGroup.LayoutParams params = null;
                if (root != null) {
                    // Create layout params that match root, if supplied
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // Set the layout params for temp if we are not
                        // attaching. (If we are, we use addView, below)
                        temp.setLayoutParams(params);
                    }
                }
                // We are supposed to attach all the views we found (int temp)
                // to root. Do that now.
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }
	.......省略代碼
        return result;
    }
}

也就是說,root!=null && attachToRoot==true,會將佈局view添加到內部,作爲它的父view,否則不會設置佈局的layoutparams,但是如果我們在使用recyclerview創建item佈局時並不需要添加到父view怎麼辦?


可以看到attachToRoot(是否附加到根佈局)只需將這個參數傳false,佈局將不會添加到root中,並且還會設置佈局的layoutparams。

調用:

LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章