关于Android开发中使用RecyclerView结合StaggeredGridLayoutManager的瀑布布局显示图片中出现异常空白的问题

在使用瀑布布局显示图片的过程中发现了一个异常情况,那就是本来高度都是warp_content的图片产生了异常空白的问题。
如图所示:
问题图片
我的子布局代码为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">

    <ImageView
        android:id="@+id/single_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:scaleType="fitCenter"
        android:src="@mipmap/appicon" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="ffdsaaaaaaaaa" />

</LinearLayout>

父布局很简单,就是一个简单的线性布局中包含了一个RecyclerView。

MainActivity中的代码为:

this.pictureRecyclerView = findViewById(R.id.picture_recycler_view);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.VERTICAL);
this.pictureRecyclerView.setLayoutManager(layoutManager);
this.pictureRecyclerAdapter = new ImageAdapter(singlePictures);
this.pictureRecyclerView.setAdapter(this.pictureRecyclerAdapter);

于是我将子布局的背景颜色设置为绿色,将图片背景颜色设置为红色,发现了问题,那就是图片的高度并没有随着StaggeredGridLayoutManager的分列而像宽度一样缩放。
如图所示,问题得到了定位:
找到了问题
找了国内好多帖子都找不到相应的办法,都说是要手动对图片进行缩放,我个人觉得这不是问题的根本。但是我在StackOverFlow上找到了灵感。那就是设置图片空间的属性

android:adjustViewBounds="true"

就可以完美解决这个问题。
解决问题后的结果为正常的瀑布布局:
解决问题
主要原理就是图片控件的adjustViewBounds性为true后,图片就会保持长宽比例的缩放,从而从根本上解决了此问题。
希望可以帮到大家,如果有问题可以添加我的QQ 1574143668 一起交流。
另外说句题外话,做安卓界面会遇到很多的问题,需要不断的去思考探究才能理解解决问题,而不是一味的百度找解决方法。

发布了8 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/kiva12138/article/details/104995492