adapter 错误的代码
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View view = LayoutInflater.from(mActivity).inflate(R.layout.item_recommend_model,parent);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
adapter正确的代码
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View view = LayoutInflater.from(mActivity).inflate(R.layout.item_recommend_model,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
解释:
View view = LayoutInflater.from(mActivity).inflate(R.layout.item_recommend_model,parent);
当我们翻开inflate源码来看
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
// 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);
}
1、此时我们的root不是null,底层默认的将attachToRoot设置为true,当attachToRoot的值为true的时候,表示我们将R.layout.item_recommend_model添加到root容器中,如果此时另外一个RecyclerView,也执行了同样的步骤R.layout.item_recommend_model又添加到了另外一个root容器里面此时就会发生崩溃。
2、当我们root不是null且我们将attachToRoot设置为false的时候,表示我们不将resource添加到root中,但是root会协助resource设置布局的参数