实际上,我想在水平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) {
}
}));
使用首选项STAP_TO_START:创建SmoothScroller
RecyclerView.SmoothScroller smoothScroller = new
LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
现在你设置了滚动的位置(项目的位置(:
smoothScroller.setTargetPosition(position);
将SmoothScroll传递到LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
我最终做了一个棘手的计算,即通过对第一个和最后一个完全可见项目进行平均来获得中间的完全可见项目。然后我应用我的逻辑如下:
代码:
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) {
}
}));
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
});