我正在尝试创建一个动态RecyclerView
布局。我正在使用GridLayoutManager
三列。
我需要包装每个网格项目并将列居中(如附件)。
我试过了StaggeredGridLayout
,我试过WrapGridLayoutManager 但这些都不起作用。
这是我的RecyclerView
:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/categories_grid"
android:layout_marginTop="@dimen/feed_item_margin"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
和我的RecyclerView
项目:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:background="@drawable/first_time_category_unselected"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:id="@+id/category_name"
android:layout_marginLeft="@dimen/feed_item_margin"
android:layout_gravity="center_vertical"
android:textColor="@color/black_colour"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/category_status_icon"
android:layout_gravity="center_vertical"
android:background="@drawable/icon_follow"
android:layout_marginLeft="@dimen/feed_item_margin"
android:layout_marginRight="@dimen/feed_item_margin"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
这是我用来实现网格间距的装饰:
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int halfSpace;
public SpacesItemDecoration(int space) {
this.halfSpace = space / 2;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getPaddingLeft() != halfSpace) {
parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
parent.setClipToPadding(false);
}
outRect.top = halfSpace;
outRect.bottom = halfSpace;
outRect.left = halfSpace;
outRect.right = halfSpace;
}
}