美文网首页自定义控件
RecyclerView item宽高无法自适应问题处理

RecyclerView item宽高无法自适应问题处理

作者: 我吃大西瓜QAQ | 来源:发表于2019-03-27 17:48 被阅读193次

最近在使用RecyclerView的时候,需要item根据内容自适应高度,但是总是出现item高度无法自适应的情况,最终问题得到解决,在此记录下。
在RecyclerView父布局中设置了Match_parent,item布局设置了wrap_content,item无法自适应高度,代码如下

  • 父布局代码
   
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="70dp"/>
  • 子布局代码
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/iv_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

实际显示出来的效果是所有item高度都一致,默认都是第一个item内容的高度自适应,造成内容显示不全或者布局显示错乱,搜索了下,发现RecyclerView常用的LinearLayoutManager并没有自适应相关的内容。

解决方法有两种:
  • 1.继承并且重写LinearLayoutManager
    -- 参考链接

  • 2.使用其他LayoutManager StaggeredGridLayoutManager

    • StaggeredGridLayoutManager是RecyclerView自带的瀑布流布局,可以设置水平或者垂直方向的布局,因此也可以用在自适应高度或者自适应宽度上,用法与创建LinearLayoutManager一样,高度自适应就设置StaggeredGridLayoutManager.HORIZONTAL,宽度自适应就设置StaggeredGridLayoutManager.VERTICAL,问题得到解决。
StaggeredGridLayoutManager horizontalManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.HORIZONTAL);
mRecyclerView.setLayoutManager(horizontalManager);

相关文章

网友评论

    本文标题:RecyclerView item宽高无法自适应问题处理

    本文链接:https://www.haomeiwen.com/subject/myrtbqtx.html