简体   繁体   中英

recycler view center selected item

I'm using RecyclerView for scrolling items horizontally. When any item is clicked , it will be selected and its background changed. What I need is when item is selected, it will scroll to center. First item will be centered at the beginning.

Any comments would be appreciated. My code is below but it doesn't center all items.

recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(getActivity(), recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, final int position) {
                    // TODO Handle item click
                    editAdapter.setSelection(position);
                    editAdapter.notifyDataSetChanged();
                    final int scrollX = (view.getLeft() - (center)) + (view.getWidth() / 2);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            recyclerView.scrollBy(scrollX, 0);
                        }
                    }, 100);
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            })
    );

in your adapter create a interface like this

 public interface NotifyPositionChange
{
    public void scrollToPosition(int position);
}

Pass an extra argument in your constructor for adapter.

public YourAdapter(NotifyPositionChange notifyPositionChange)
{
  this.notifyPosition=notifyPositionChange;
}

call method of interface when item is selected in adapter like this

notifyPositionChange.scrollToPosition(position);

pass your current position. And in your activity implement this interface and override its method.

 @Override
public void scrollToPosition(int position) {

        yourRecyclerView.getLayoutManager().smoothScrollToPosition(yourRecyclerView, null, position - 1);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM