RecycleView多条目布局不填充满父布局
今天写了一个Recycleview 的多条目布局,有部分子布局无法填充满父布局。如下图
最后发现是犹豫在
onCreateViewHolder方法里视图是这样填充的。
View view = View.inflate(mContext, R.layout.item_rcy_top, null);
改为
View view = LayoutInflater.from(mContext).inflate(R.layout.item_rcy_top, parent, false);完美解决视图问题。
深究其原因:
if (root != null) {
// 系统根据父布局生成layoutParams
params = root.generateLayoutParams(attrs);
// 如果不添加到父布局,则添加layoutParams
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
parent不传空,attachToRoot传true:
// 如果父布局不空,且添加到父布局
if (root != null && attachToRoot) {
root.addView(temp, params);
}
parent传空,则只是inflate布局,但并不会添加layout参数.
这个方法
View view = View.inflate(mContext, R.layout.item_rcy_top, null);
内部使用的这个:LayoutInflater.inflate(resource, root, root != null)
等于parent传空