GridLayoutManager上用于RecyclerView的正方形布局 [英] Square layout on GridLayoutManager for RecyclerView

查看:737
本文介绍了GridLayoutManager上用于RecyclerView的正方形布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用正方形图像进行网格布局.我认为必须可以通过操纵onMeasure来操作

I try to make a grid-layout with square images. I thought that it must be possible to manipulate the GridLayoutManager by manipulating onMeasure to do a

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

代替

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

但不幸的是,这没有用.

but unfortunately, that didn't work.

有什么想法吗?

推荐答案

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

To have the square elements in my RecyclerView, I provide a simple wrapper for my root View element; I use the following SquareRelativeLayout in place of 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布局中,我刚刚引用了自定义视图,如下所示.不过,您也可以通过编程方式执行此操作.

Then, in my XML layout for the adapter, I've just referenced the custom view as shown in the following. Though, you can do this programmatically also.

<?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).

Note: Depending on which orientation your grid is, then you may want to have the width based off of height (GridLayoutManager.HORIZONTAL) instead of the height being based off the width (GridLayoutManager.VERTICAL).

这篇关于GridLayoutManager上用于RecyclerView的正方形布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆