要使RecyclerView水平居中,可以通过以下步骤实现:
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
public class CenterItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int parentWidth = parent.getWidth();
int itemWidth = view.getWidth();
int margin = (parentWidth - itemWidth) / 2;
outRect.set(margin, 0, margin, 0);
}
}
recyclerView.addItemDecoration(new CenterItemDecoration());
这样,RecyclerView中的Item就会水平居中显示了。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)
领取专属 10元无门槛券
手把手带您无忧上云