我尝试用方形图像制作网格布局。我认为必须可以通过操纵 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/