简体   繁体   English

回收商查看中心选定的项目

[英]recycler view center selected item

I'm using RecyclerView for scrolling items horizontally. 我正在使用RecyclerView水平滚动项目。 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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