我有一些物品的回收查看,我想获得屏幕中间项目的索引。现在我只能看到第一个项目的项目索引中间可见,最后一个项目可见。
这是截图: image
这是代码
myList = (RecyclerView) v.findViewById(R.id.frag_penampilanobat_pilih_bentuk);
final LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
itemWidth = getResources().getDimension(R.dimen.item_width);
padding = (size.x - itemWidth) / 2;
firstItemWidth = getResources().getDimension(R.dimen.padding_item_width);
allPixels = 0;
ExtraItemsAdapter bentuk_adapter = new ExtraItemsAdapter(0, clone, padding);
myList.setAdapter(bentuk_adapter);
myList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstPos = layoutManager.findFirstVisibleItemPosition();
int lastPos = layoutManager.findLastVisibleItemPosition();
int middle = (Math.abs(lastPos - firstPos) / 2 + firstPos) + 1;
pos_icon_bentuk = middle;
source = getActivity().getResources().getDrawable(pengingat_obat_helper.getDrawable(pos_icon_shape));
bentuk_obat.setBackground(FormatShapeColor.setColor(getActivity(), getColor(), source, pos_icon_warna_1));
}
});
我不知道该怎么做。有人有意见吗?任何答案将不胜感激。 对不起我的英语不好, 感谢
答案 0 :(得分:0)
据我所知,你需要中间。这是我的解决方案。
int firstPos = layoutManager.findFirstVisibleItemPosition();
int lastPos = layoutManager.findLastVisibleItemPosition();
int centerRecyclerView = activityMainBinding.recyclerView.getWidth() / 2;
int minDelta=Integer.MAX_VALUE;
int middle = 0;
for(int i=firstPos;i<=lastPos;i++) {
View view = layoutManager.findViewByPosition(i);
if(view!=null) {
int positionCenterView = view.getLeft() + (view.getRight() - view.getLeft()) / 2;
int delta = Math.abs(centerRecyclerView - positionCenterView);
if(delta<minDelta)
{
minDelta=delta;
middle =i;
}
}
}