RecyclerView GridLayoutManager 布局居中

Adapter布局中外层View设置

android:layout_width="match_parent"

android:gravity="center_horizontal"

MVVM中

Activity 布局

...

app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"

app:spanCount="3"/>


Activity:

RecyclerView.addItemDecoration(SpaceItemDecoration(this,ScreenUtil.dip2px(8.0f)))


SpaceItemDecoration.java


public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

private int spacing =0;

private Context context;

public SpaceItemDecoration(Context context) {

this.context = context;

spacing = context.getResources().getDimensionPixelSize(R.dimen.ktv_item_channel_spacing);

}

public SpaceItemDecoration(Context context,int spacing) {

this.context = context;

this.spacing = spacing;

}

@Override

    public void getItemOffsets(@NonNull Rect outRect,@NonNull View view,

@NonNull RecyclerView parent,@NonNull RecyclerView.State state) {

super.getItemOffsets(outRect, view, parent, state);

outRect.set(spacing,spacing,spacing,spacing);

}

}

你可能感兴趣的:(RecyclerView GridLayoutManager 布局居中)