android - 具有 2 列和自动调整大小的图像的 RecyclerView

标签 android android-studio android-recyclerview

我有一个有两列的 recyclerView,我想显示不同高度的图像。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="2dp"
android:layout_marginRight="3dp"
android:layout_marginBottom="2dp">

<android.support.v7.widget.CardView
    android:id="@+id/card_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#f7f5f5"
    app:cardCornerRadius="10dp">

    <ImageView
        android:id="@+id/image_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:srcCompat="@tools:sample/avatars" />
</android.support.v7.widget.CardView>

并加载图像。

  RecyclerView recycler_item =  main.findViewById(R.id.recycler_item);
  recycler_item.setHasFixedSize(false);
  recycler_item .setLayoutManager(new GridLayoutManager(context, 2));
  recycler_item .setAdapter(itemAdapter);
  LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation);
  recycler_item.setLayoutAnimation(animation);
  itemAdapter.notifyDataSetChanged();
  recycler_item.scheduleLayoutAnimation();

结果是

enter image description here

但我想这样显示

enter image description here

最佳答案

首先,为 ImageView 设置 android:adjustViewBounds="true" 属性以调整其边界以保持其可绘制对象的纵横比。

现在,是时候使用 StaggeredGridLayoutManager 的实例了作为 RecyclerView 的布局管理器来实现结果。

StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recycler_item.setLayoutManager(layoutManager);

关于android - 具有 2 列和自动调整大小的图像的 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545618/

相关文章:

android - RecyclerView 适配器中的 LayoutInflater

scroll - 隐藏 RecyclerView 滚动条上的 FloatingActionButton

android - 使用 EncryptedSharedPreferences 时是否应使用任何 proguard 规则?

android - 按下后仅删除 fragment

java - 在 Android 中使用 JCIFS

android - 以编程方式获取模块名称

java - 如何在Gradle中指定模块的JDK编译级别

android - Recyclerview + 内容提供者 + CursorLoader

android - 使用 fragment 改变方向 - 错误的 Activity 开始

Android 位图限制 - 防止 java.lang.OutOfMemory