android - RecyclerView 的 GridLayoutManager 上的方形布局

标签 android android-recyclerview gridlayoutmanager

我尝试用方形图像制作网格布局。我认为必须可以通过操纵 onMeasure 来操纵 GridLayoutManager 来做一个

super.onMeasure(recycler, state, widthSpec, widthSpec); 

而不是

super.onMeasure(recycler, state, widthSpec, heightSpec);

但不幸的是,这没有用。

有什么想法吗?

最佳答案

为了在我的 RecyclerView 中包含方形元素,我为我的根 View 元素提供了一个简单的包装器;我使用以下 SquareRelativeLayout 代替 RelativeLayout

package net.simplyadvanced.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/** A RelativeLayout that will always be square -- same width and height,
 * where the height is based off the width. */
public class SquareRelativeLayout extends RelativeLayout {

    public SquareRelativeLayout(Context context) {
        super(context);
    }

    public SquareRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(VERSION_CODES.LOLLIPOP)
    public SquareRelativeLayout(Context context, AttributeSet attrs,         int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Set a square layout.
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

}

然后,在我的适配器 XML 布局中,我刚刚引用了自定义 View ,如下所示。不过,您也可以通过编程方式执行此操作。

<?xml version="1.0" encoding="utf-8"?>
<net.simplyadvanced.widget.SquareRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/elementRootView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <!-- More widgets here. -->

</net.simplyadvanced.widget.SquareRelativeLayout>

注意:根据您的网格的方向,您可能希望宽度基于高度 (GridLayoutManager.HORIZONTAL) 而不是高度基于宽度 ( GridLayoutManager.VERTICAL).

关于android - RecyclerView 的 GridLayoutManager 上的方形布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566954/

相关文章:

android - 如何从右到左用GridLayoutManager填充RecyclerView

java - Intent.createChooser 选择默认应用程序

android - RecyclerView.setItemViewCacheSize 和 RecycledViewPool.setMaxRecycledViews 有什么区别?

java - RecyclerView onScrolled 根本没有被触发

android - RecyclerView 仅显示来自 Firebase 的一项

android - 卡片尺寸不同

android - 如何捕捉与 RecyclerView 一起使用的 ItemTouchHelper 的 Drop Action

Android - 使 SoundPool 成为全局类? (适用于所有其他类(class))

Android Studio 3.6 测试框架意外退出,编排器崩溃

java - 使用 Appium 向下滚动时出现 "An unknown server-side error occurred while processing the command"