如何在点击时滚动水平recyclerview?

时间:2018-08-03 05:00:36

标签: android android-recyclerview horizontal-scrolling

实际上,我想在水平recyclerview中添加一个这样的功能,如果它是最后一个位置,它会自动滚动到下一个位置,有时它必须向前移动,有时它必须像instagram的过滤器一样向后移动单击可以自动滚动的视图。我不知道如何执行此任务。目前,根据我的逻辑,它只是向前滚动,但我不知道如何为向后滚动插入逻辑。

代码:

horzRview.addOnItemTouchListener(new RecyclerItemClickListener(ctx, horzRview, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            if(position<adapter.getItemCount()-1)
            horzRview.getLayoutManager().smoothScrollToPosition(horzRview, null, position+1);

            else horzRview.getLayoutManager().smoothScrollToPosition(horzRview, null, position-1);

        }

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

3 个答案:

答案 0 :(得分:1)

使用首选项STAP_TO_START创建SmoothScroller:

RecyclerView.SmoothScroller smoothScroller = new 
LinearSmoothScroller(context) {
   @Override protected int getVerticalSnapPreference() {
       return LinearSmoothScroller.SNAP_TO_START;
   }
};

现在,您可以设置滚动位置(其项目的位置):

smoothScroller.setTargetPosition(position);

将该SmoothScroller传递给LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);

答案 1 :(得分:0)

public interface OnItemClickListener {
void onItemClick(View view , int position);
}
//in adapter class
public class Adpt extends 
RecyclerView.Adapter<Adpt.ViewHolder> {
Context context;
OnItemClickListener onItemClickListener;
public Adpt(Context context,OnItemClickListener onItemClickListener) {
this.context = context;
this.onItemClickListener = onItemClickListener;
}
//put your click on itemview 
holder.itemView.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {

      onItemClickListener.onItemClick(view,position);


  }
});
//implement your interface when you will set your adapter
Adpt adpt = new Adpr(activity,new OnItemCLickListner(){
// put your logic here
});

答案 2 :(得分:0)

我最终做了一个棘手的计算,即通过对第一个和最后一个完全可见的项进行平均,得到中间完全可见的项。然后我按如下方式应用我的逻辑:

代码:

horzRview.addOnItemTouchListener(new RecyclerItemClickListener(ctx, horzRview, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

            int avg =
                    (layoutManager.findFirstCompletelyVisibleItemPosition()+(layoutManager.findFirstCompletelyVisibleItemPosition()+1)+
                    layoutManager.findLastCompletelyVisibleItemPosition())/3;


            if(position>avg) horzRview.getLayoutManager().smoothScrollToPosition(horzRview, null, position+1);
            else if(position!=0) horzRview.getLayoutManager().smoothScrollToPosition(horzRview, null, position-1);
            else horzRview.getLayoutManager().smoothScrollToPosition(horzRview, null, 0);

        }

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