Backlight87
10/18/2017 - 9:21 AM

双层嵌套的recycleView

1、其实原理是一样的,就是在外层recycle的adapter的viewHolder里,实例化下一个recycleView,进行初始化以及赋予适配器,不过能不用还是不用,嵌套多层交互太复杂了,以及容易发生滑动冲突 2、【bug】里层(内层)recycleView显示数据不完全


解决方法:
在里层适配器的onCreateViewHolder方法中
在填充该item布局的时候viewgroup填写null
LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_grid, null, false);

原因:填写viewgroup的时候会利用viewgroup的根节点参数去填充布局,不填写则会默认用空的参数去填充,这样才能展示完整。

如果以上方式还是显示不全,那就在createViewHolder()的时候去直接计算并指定内部RecyclerView的Height。


public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_grid, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mTextView.setText("Grid "+position);
      }

    @Override
    public int getItemCount() {
        return 8;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final AppCompatTextView mTextView;

         public ViewHolder(View itemView) {
            super(itemView);
             mTextView= (AppCompatTextView) itemView.findViewById(R.id.textView);
         }
    }
}


//需要注意的是GridLayoutManager要设置setAutoMeasureEnabled(true)成自适应高度
//onBindViewHolder 中需要判断item中recyclerview是否已经设置适配器,重复设置会导致滑动不流畅
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.ViewHolder> {
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_main, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mButton.setText("Item " + position);
        if(holder.mRecyclerView.getAdapter()==null) {
            holder.mRecyclerView.setAdapter(new GridAdapter());
        }/*else {
            holder.mRecyclerView.getAdapter().notifyDataSetChanged();
        }*/

    }

    @Override
    public int getItemCount() {
        return 10;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final AppCompatButton mButton;
        public final RecyclerView mRecyclerView;

        public ViewHolder(View itemView) {
            super(itemView);
            mButton = (AppCompatButton) itemView.findViewById(R.id.button);
            mRecyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerView);
            RecyclerView.LayoutManager manager = new GridLayoutManager(itemView.getContext(), 4);
            manager.setAutoMeasureEnabled(true);
            mRecyclerView.setLayoutManager(manager);
        }
    }
}