建个人免费网站用哪个,手机版网站开发人员选项,扫码进网页怎么制作,短视频seo公司RecyclerView滚动到指定位置并置顶
RecyclerView本身提供了几个定位的方法#xff0c;除了手动滑动的scrollTo#xff0c;smootScrollTo和scrollBy#xff0c;smoothScrollBy方法之外#xff0c;有一个直接滑动到指定位置item的scrollToPosition方法和另一个在此基础上平滑…RecyclerView滚动到指定位置并置顶
RecyclerView本身提供了几个定位的方法除了手动滑动的scrollTosmootScrollTo和scrollBysmoothScrollBy方法之外有一个直接滑动到指定位置item的scrollToPosition方法和另一个在此基础上平滑滚动的smoothScrollToPosition方法。但是经实验该方法只能保证指定位置的item滑动到屏幕可见如果指定的item本来就已在屏幕可见范围则不会滑动并且屏幕外的item滑到可见范围后还需手动置顶。
常见处理方式
看了网上大多数相关的博客一般的处理都是将item区分为 在可见范围以上/在可见范围内/在可见范围以下 三种情况分别进行处理。
1、item在第一个可见item之前直接用smoothScrollToPosition则当该item移动到可见范围时它就在RecyclerView顶部
2、item在可见范围内即在第一个可见item之后最后一个可见item之前那么这时scrollToPosition失效需要手动计算该item的view距离顶部的距离用scrollBy自行移动到置顶位置
3、item在最后一个可见item之后用smoothScrollToPosition滑动到可见范围 (此时该item在最后一个位置)再获取该item的view计算到顶部距离再监听RecyclerView的滑动对其进行二次滑动到顶部
贴上该方法主要的实现代码
//标记是否需要二次滑动private boolean shouldMove;//需要滑动到的item位置private int mPosition;/*** RecyclerView滑动到指定item函数*/private void smoothMoveToPosition(RecyclerView recyclerView, final int position) {// 获取RecyclerView的第一个可见位置int firstItem recyclerView.getChildLayoutPosition(recyclerView.getChildAt(0));// 获取RecyclerView的最后一个可见位置int lastItem recyclerView.getChildLayoutPosition(recyclerView.getChildAt(mRecyclerView.getChildCount() - 1));if (position firstItem) {// 指定item在第一个可见item之前recyclerView.smoothScrollToPosition(position);} else if (position lastItem) {// 指定item在可见范围内即在第一个可见item之后最后一个可见item之前int position position - firstItem;if (position 0 position recyclerView.getChildCount()) {// 计算指定item的view到顶部的距离int top recyclerView.getChildAt(position).getTop();// 手动滑动到顶部recyclerView.smoothScrollBy(0, top);}} else {// 指定item在最后一个可见item之后用smoothScrollToPosition滑动到可见范围// 再监听RecyclerView的滑动对其进行二次滑动到顶部recyclerView.smoothScrollToPosition(position);mPositon position;shouldMove true;}}…………/*** 监听RecyclerView的滑动对需要进行二次滑动的item进行滑动**/mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {Overridepublic void onScrollStateChanged(RecyclerView recyclerView, int newState) {super.onScrollStateChanged(recyclerView, newState);if ( shouldMove RecyclerView.SCROLL_STATE_IDLE newState) {shouldMove false;smoothMoveToPosition(mRecyclerView, mPosition);}}});本文推荐的另外一种处理方式
通过上面的代码可以看出来这种处理方式比较麻烦而且处理逻辑需要分成两块并不够直观。因此点开源码发现实际上RecyclerView在用smoothScrollToPosition函数时是创建了一个LinearSmoothScroller 再继续点开看 一进入文件就发现了SNAP_TO_START这个参数注释意思是将子view与父view左对齐或顶部对齐其中是左对齐还是顶部对齐是根据LayoutManager是horizontal还是vertical决定因此重写LinearSmoothScroller设置该参数即可实现置顶。
public class TopSmoothScroller extends LinearSmoothScroller {TopSmoothScroller(Context context) {super(context);}Overrideprotected int getHorizontalSnapPreference() {return SNAP_TO_START;}Overrideprotected int getVerticalSnapPreference() {return SNAP_TO_START; // 将子view与父view顶部对齐}
}之后获取RecyclerView的LayoutManager调用startSmoothScroll即可
final TopSmoothScroller mTopScroller new TopSmoothScroller(this);
mTopScroller.setTargetPosition(position);
mRecyclerView.getLayoutManager.startSmoothScroll(mTopScroller);