短视频app源码,日常开发之RecycleView滑动
短视频app源码,日常开发之RecycleView滑动
一、使用recyclerview.scrollToPosition(index)滑动布局,结果定位不准确
解决办法:
//使用LayoutManager滑动位置并设置offset为0,可以保证滑动的位置正确
mLayoutManager.scrollToPositionWithOffset(index, 0);
二、区分手动滑动和代码滑动
/**
* @author : zhn
* @date : 2022/7/1 18:02
* description :滑动监听,判断是不是用户自己手动滑动
*/
public class ScrollListenerRecyclerView extends RecyclerView {
//用户触发的滑动含filling状态
private boolean userScroll;
//用户拖动
private boolean userTouch;
public ScrollListenerRecyclerView(@NonNull Context context) {
super(context);
}
public ScrollListenerRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ScrollListenerRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mListener != null) {
mListener.onScrollChanged(userScroll, l, t, oldl, oldt);
}
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
if (state == SCROLL_STATE_IDLE && !userTouch) {
userScroll = false;
}
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_MOVE) {
userTouch = true;
userScroll = true;
} else if (e.getAction() == MotionEvent.ACTION_UP) {
userTouch = false;
}
return super.onTouchEvent(e);
}
public interface ScrollChangeListener {
void onScrollChanged(boolean fromUser, int l, int t, int oldl, int oldt);
}
private ScrollChangeListener mListener;
public void setListener(ScrollChangeListener listener) {
mListener = listener;
}
}
用法:
mBinding.rlvCourseDetail.setListener(new ScrollListenerRecyclerView.ScrollChangeListener() {
@Override
public void onScrollChanged(boolean fromUser, int l, int t, int oldl, int oldt) {
if (fromUser) {
scrollSwitchTab();
}
}
});
以上就是短视频app源码,日常开发之RecycleView滑动, 更多内容欢迎关注之后的文章