gpt4 book ai didi

android - 第一个项目中心在 RecyclerView 中的 SnapHelper 中对齐

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:25 30 4
gpt4 key购买 nike

我在 RecyclerView 中使用 PagerSnapHelper。RecyclerView 中屏幕左侧位置的第一项。我需要居中对齐的第一项。

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);

enter image description here

最佳答案

您可以使用 ItemDecoration,下面的代码适用于第一个和最后一个项目,还支持边距。

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;
}
}

关于android - 第一个项目中心在 RecyclerView 中的 SnapHelper 中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425002/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com