在Recycleview中,通过 onCreateViewHolder 回调函数中创建 item 的view对象,如果创建方式为:
View view = View.inflate(context, layoutId, null);
或者
LayoutInflater factory = LayoutInflater.from(context);
View view = factory.inflate(layoutId, null);
这里需要注意,获取的 View 对象,其LayoutParams为空,如果直接使用会发现布局出现大小不对的情况。
解决方案为手动创建LayoutParams对象并赋值给View对象。
View view = View.inflate(context, layoutId, null);
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT);
view.setLayoutParams(layoutParams);
或者通过如下方式创建View对象,但是需要传递View的父控件对象,并且
attachToRoot参数要设置为false
LayoutInflater factory = LayoutInflater.from(parent.getContext());
View view = factory.inflate(layoutId, parent, false);
方法原型如下:
public