RecyclerView根据内容多少动态设置高度

在项目开发中我们经常会遇到需要RecyclerView和ScrollViewq嵌套的情况,一般我们都需要把RecyclerView中的内容全部显示,然后设置RV的高度为所有内容的高度+RV Padding+item 之间的Divider。
原理很简单,实现起来也很简单。

  • 创建RV ViewHolder

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public abstract class  MyViewHolder extends RecyclerView.ViewHolder {

    TextView tv_item;
    ImageView img_delete_item;

    public MyViewHolder(View itemView) {
    super(itemView);
    tv_item = (TextView) itemView.findViewById(R.id.tv_single);
    img_delete_item = (ImageView) itemView.findViewById(R.id.img_toprecycle_delete);
    }


    public abstract void setFixedHeight();
    }
  • 实现自定义VH

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public MyViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.item_useview, parent, false);
    MyViewHolder viewHolder = new MyViewHolder(view){
    @Override
    public void setFixedHeight() {
    // magic happening here
    ViewGroup.LayoutParams parentParams = parent.getLayoutParams();
    parentParams.height =
    ((RecyclerView) parent).computeVerticalScrollRange()
    + parent.getPaddingTop()
    + parent.getPaddingBottom();
    parent.setLayoutParams(parentParams);
    }
    };

    return viewHolder;
    }
  • 设置RV高度

    1
    2
    3
    4
    //绑定viewholder
    public void onBindViewHolder(MyViewHolder holder, final int position) {
    holder.setFixedHeight();
    }
分享到