[英]How to align RecyclerView Grid Layout Items to the left with fixed number of columns?
I have a recyclerview with grid layout in which I want to align items to the left with fixed number of columns.我有一个带有网格布局的recyclerview,我想在其中将项目与固定列数对齐。
Currently,the recyclerview grid layout divides the width into number of items and places them in equal margins.目前,recyclerview 网格布局将宽度划分为项目数,并将它们放置在相等的边距中。
Here's my code:这是我的代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_grid_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ripple_background"
android:clickable="true"
android:layout_marginStart="@dimen/grid_2"
android:layout_marginLeft="@dimen/grid_2"
android:padding="@dimen/layout_margin_5dp"
android:layout_marginTop="@dimen/layout_margin_param_1" >
<com.carwale.carwale.ui.widgets.CarwaleTextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/iv_grid_item_image"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="@color/warm_grey"
android:ellipsize="end"
android:textSize="@dimen/font_h4"
android:visibility="gone"
android:singleLine="true" />
</RelativeLayout>
RecyclerView recyclerGridLayout = new RecyclerView(mContext);
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
recyclerGridLayout.setHasFixedSize(true);
int spanCount = 4; // 3 columns
int rowSpacing = getResources().getDimensionPixelSize(20);
int columnSpacing = getResources().getDimensionPixelSize(6);
recyclerGridLayout.addItemDecoration(new GridSpacingItemDecoration(spanCount, rowSpacing, columnSpacing));
recyclerGridLayout.setNestedScrollingEnabled(false);
recyclerGridLayout.setLayoutManager(new GridLayoutManager(mContext, spanCount));
GridLayoutAdapter gridLayoutAdapter = new GridLayoutAdapter(mContext);
recyclerGridLayout.setAdapter(gridLayoutAdapter);
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item columngrid
outRect.left = column * columnSpacing / spanCount; // column * ((1f / spanCount) * rowSpacing)
outRect.right = columnSpacing - (column + 1) * columnSpacing / spanCount; // rowSpacing - (column + 1) * ((1f / spanCount) * rowSpacing)
if (position >= spanCount) {
outRect.top = rowSpacing; // item top
}
}
Every time the user clicks on the Item modify the RecyclerView
dataset array based on the order in which the user clicks and call RecyclerView adapter.notifyDatasetchanged()
每次用户单击 Item 时,根据用户单击的顺序修改
RecyclerView
数据集数组并调用 RecyclerView adapter.notifyDatasetchanged()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.