本文介绍了第一个项目中心在RecyclerView中的SnapHelper中对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在RecyclerView中使用PagerSnapHelper.RecyclerView中的第一项位于屏幕的左侧.我需要居中对齐的第一项.
I'm using PagerSnapHelper in RecyclerView.the first item in RecyclerView in left position in the screen.I need the first item in center aligns.
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
PagerSnapHelper snapHelper = new PagerSnapHelper();
binding.recyclerView.setOnFlingListener(null);
snapHelper.attachToRecyclerView(binding.recyclerView);
binding.recyclerView.setLayoutManager(layoutManager);
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setItemAnimator(new DefaultItemAnimator());
binding.recyclerView.setAdapter(mAdapter);
推荐答案
您可以使用ItemDecoration,以下代码适用于第一个和最后一个项目,并且还支持边距.
You can use ItemDecoration, below codes work for the first and last item and also support margin.
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
public class OffsetItemDecoration extends RecyclerView.ItemDecoration {
private Context ctx;
public OffsetItemDecoration(Context ctx) {
this.ctx = ctx;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int offset = (int) (getScreenWidth() / (float) (2)) - view.getLayoutParams().width / 2;
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (parent.getChildAdapterPosition(view) == 0) {
((ViewGroup.MarginLayoutParams) view.getLayoutParams()).leftMargin = 0;
setupOutRect(outRect, offset, true);
} else if (parent.getChildAdapterPosition(view) == state.getItemCount() - 1) {
((ViewGroup.MarginLayoutParams) view.getLayoutParams()).rightMargin = 0;
setupOutRect(outRect, offset, false);
}
}
private void setupOutRect(Rect rect, int offset, boolean start) {
if (start) {
rect.left = offset;
} else {
rect.right = offset;
}
}
private int getScreenWidth() {
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
}
这篇关于第一个项目中心在RecyclerView中的SnapHelper中对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!