我尝试使用方形图像制作网格布局。我认为必须通过操纵GridLayoutManager
来操纵onMeasure
来操纵
super.onMeasure(recycler, state, widthSpec, widthSpec);
而不是
super.onMeasure(recycler, state, widthSpec, heightSpec);
但不幸的是,这不起作用。
有什么想法吗?
答案 0 :(得分:147)
为了在我的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
)的高度。 / p>
答案 1 :(得分:47)
约束布局解决了这个问题。使用app:layout_constraintDimensionRatio="H,1:1"
<强> recyclerview_grid_layout.xml 强>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="H,1:1"
android:scaleType="centerCrop"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
答案 2 :(得分:18)
如果有人想要以不同方式缩放视图 - 您就是这样做的:
private static final double WIDTH_RATIO = 3;
private static final double HEIGHT_RATIO = 4;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = (int) (HEIGHT_RATIO / WIDTH_RATIO * widthSize);
int newHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, newHeightSpec);
}
答案 3 :(得分:6)
启动API 26(支持库26.0),可以使用公开宽高比属性的ConstraintLayout强制视图被平方: https://developer.android.com/training/constraint-layout/index.htm
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
...
}
...
dependencies {
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta1' //use whatever version is current
}
我在GridLayoutManager中使用的布局示例:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/margin_small"
android:background="@drawable/border_gray"
android:gravity="center">
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="h,1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<!-- place your content here -->
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
app:layout_constraintDimensionRatio="h,1:1"
是此处的关键属性
答案 4 :(得分:2)
请尝试使用FrameLayout的这个扩展名。它执行双重测量以提高一致性。它还支持自定义XML属性,以便从布局
设置所需的宽高比public class StableAspectFrameLayout extends FrameLayout {
private int aspectWidth = 1;
private int aspectHeight = 1;
public StableAspectFrameLayout(Context context) {
this(context, null, 0);
}
public StableAspectFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StableAspectFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
extractCustomAttrs(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public StableAspectFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
extractCustomAttrs(context, attrs);
}
private void extractCustomAttrs(Context context, AttributeSet attrs) {
if (attrs == null) return;
TypedArray a = context.getResources().obtainAttributes(attrs, R.styleable.StableAspectFrameLayout);
try {
aspectWidth = a.getInteger(R.styleable.StableAspectFrameLayout_aspect_width, 1);
aspectHeight = a.getInteger(R.styleable.StableAspectFrameLayout_aspect_height, 1);
} finally {
a.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int newSpecWidth = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
int newH = Math.round(((float) getMeasuredWidth()) * aspectHeight / aspectWidth);
int newSpecHeigh = MeasureSpec.makeMeasureSpec(newH, MeasureSpec.EXACTLY);
super.onMeasure(newSpecWidth, newSpecHeigh);
}
}
attrs.xml
的内容<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- StableAspectFrameLayout -->
<declare-styleable name="StableAspectFrameLayout">
<attr name="aspect_width" format="integer"/>
<attr name="aspect_height" format="integer"/>
</declare-styleable>
</resources>
答案 5 :(得分:1)
我再次推荐相对较新的百分比&#39;布局。使用依赖项'com.android.support:percent:25.2.0'
,您可以执行以下操作:
<android.support.percent.PercentFrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image"
app:layout_widthPercent="100%"
app:layout_aspectRatio="100%"
android:padding="10dp"
android:scaleType="centerCrop"
android:cropToPadding="true"
tools:background="#efdbed"
/>
</android.support.percent.PercentFrameLayout>
它可能比ConstraintLayout快得多,虽然总有一天我们可能不再关心了。
答案 6 :(得分:1)
针对Androidx的ConstraintLayout的小更新。
将此行包括在您的build.gradle中:
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta2'
我想使用带有方形CardViews的GridLayoutManager获得RecycleView,并且我将这样的布局用于项目:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="0dp"
android:layout_height="0dp"
card_view:cardElevation="4dp"
app:layout_constraintDimensionRatio="H,1:1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
>
在ConstraintLayout上
在子节点上,以我的情况为CardView
请参阅offsite上的一些详细说明。
答案 7 :(得分:0)
我不喜欢选择的答案,所以让我提供我的:不是将整个项目布局包装在SomeDammyLayoutWithFixedAspectRatio中,而是可以破解GridLayoutManager并在measureChild中重写代码。我已经取代了这些内容:
if (mOrientation == VERTICAL) {
wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
horizontalInsets, lp.width, false);
hSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getHeightMode(),
verticalInsets, lp.height, true);
} else {
hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
verticalInsets, lp.height, false);
wSpec = getChildMeasureSpec(mOrientationHelper.getTotalSpace(), getWidthMode(),
horizontalInsets, lp.width, true);
}
到:
if (mOrientation == VERTICAL) {
wSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
horizontalInsets, lp.width, false);
hSpec = wSpec;
} else {
hSpec = getChildMeasureSpec(availableSpaceInOther, otherDirParentSpecMode,
verticalInsets, lp.height, false);
wSpec = hSpec;
}
似乎工作正常。
不要误解我,这也很混乱,但至少这个解决方案并没有通过扩展视图层次来损害应用程序性能
答案 8 :(得分:0)
我有类似的问题,我不得不在视图中对视图进行充气,该视图在回收站视图的网格中是正方形的。以下是我的做法。
在onCreateViewHolder方法中,我使用ViewTreeObserver和GlobalLayoutListener来获取布局的测量宽度。布局在width属性中具有match_parent值。我的任何回收者视图的中心水平布局。
final View view = LayoutInflater.from(mActivity).inflate(R.layout.list_item_deals, parent, false);
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int side = view.getMeasuredWidth();
ViewGroup.LayoutParams lp = view.getLayoutParams();
lp.width = side;
lp.height = side;
view.setLayoutParams(lp);
}
});