android – GridLayoutManager for RecyclerView的Square布局
作者:互联网
我尝试使用方形图像制作网格布局.我认为必须可以通过操作onMeasure来操作GridLayoutManager
super.onMeasure(recycler, state, widthSpec, widthSpec);
代替
super.onMeasure(recycler, state, widthSpec, heightSpec);
但不幸的是,这没有用.
有任何想法吗?
解决方法:
为了在我的RecyclerView中使用方形元素,我为我的根视图元素提供了一个简单的包装器;我使用以下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布局中,我刚刚引用了自定义视图,如下所示.不过,您也可以通过编程方式执行此操作.
<?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,android-recyclerview,gridlayoutmanager 来源: https://codeday.me/bug/20190925/1817467.html