在中心的RecyclerItemClickListener捕捉项目上

时间:2019-03-19 15:34:49

标签: android android-recyclerview horizontal-scrolling

当我单击项目时,我想在recylerview中滚动,以使该项目位于中心完全可见,而其他项目则部分可见。 (如第一张图片所示)

我试图在scroll(fling)上做得很好,但是当我点击项目尝试时却不起作用。 (如第二张图片所示)

 mSnapHelper = new LinearSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                View centerView = findSnapView(layoutManager);
                if (centerView == null)
                    return RecyclerView.NO_POSITION;

                int position = layoutManager.getPosition(centerView);
                int targetPosition = -1;
                if (layoutManager.canScrollHorizontally()) {
                    if (velocityX < 0) {
                        targetPosition = position - 1;
                    } else {
                        targetPosition = position + 1;
                    }
                }

                final int firstItem = 0;
                final int lastItem = layoutManager.getItemCount() - 1;
                targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
                return targetPosition;
            }
        };
        mImagesRecyclerView.setLayoutManager(mLayoutManager);
        mSnapHelper.attachToRecyclerView(mImagesRecyclerView);

        mImagesRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Log.d("position", "" + position);
                        mImagesRecyclerView.scrollToPosition(position);
                        mImageAdapter.setSelected(position);
                    }
                })
        );

        mImagesRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int snapPosition = mLayoutManager.getPosition(mSnapHelper.findSnapView(mLayoutManager));
                mImageAdapter.setSelected(snapPosition);
            }

        });

enter image description here enter image description here

0 个答案:

没有答案