我有一个全屏网格布局,包含8行7 ImageView。 我需要所有行都居中,行之间没有空格(现在,我已经上传了图像)。空格只能在顶部和底部。我已经尝试在Internet上找到一种解决方案,但没有找到。
XML:
}}
我尝试将所有ImageViews的高度设置为与宽度相同的解决方案,但是我的代码无法正常工作
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridLayout
android:id="@+id/gameGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:rowCount="8"
android:columnCount="7"
>
<!-- ROW 1-1 -->
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/cellR1-1"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
app:srcCompat="@drawable/dl"
/>
<!-- ROW 1-2 -->
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/cellR1-2"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
app:srcCompat="@drawable/dl"
/>
<!-- ROW ... -->
</GridLayout>
</RelativeLayout>
答案 0 :(得分:1)
使用RecyclerView代替GridLayout可能对您有所帮助
RecyclerView.LayoutManager recyclerViewLayoutManager = new GridLayoutManager(getApplicationContext(), 7); // 7 means how many column you want you can change according to your requirement.
recyclerView.setLayoutManager(recyclerViewLayoutManager);
答案 1 :(得分:1)
尝试将RecyclerView与GridLayoutManager一起使用,如下所示:
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 7);
YourAdapter adapter = new YourAdapter();
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
int spacing = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
Objects.requireNonNull(getContext()).getResources().getDisplayMetrics());
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == Objects.requireNonNull(parent.getAdapter()).getItemCount() - 1) {
outRect.bottom = spacing;
}
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = spacing;
}
}
});
其他解决方案是:
只需将填充添加到RecyclerView的顶部和底部,然后将clipToPadding
属性设置为false
,就不必在顶部和底部都添加填充。
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingTop="8dp"
android:paddingBottom="8dp" />