序言
在垂直滑动的过程中可以横向滚动内容。
效果
代码
就一个工具类就行了。可以通过root view向上查找recycleView。自动添加滚动监听。在子view完全显示出来以后,才分发滚动事件。这样用户才能看清楚第一个。
需要一个id资源
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="key_rv_scroll_helper" type="id"/>
</resources>
RVScrollHelper
package com.trs.myrb.provider.scroll;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.trs.myrb.R;
import com.trs.myrb.douyin.action.TRSFunction;
/**
* <pre>
* Created by zhuguohui
* Date: 2023/5/12
* Time: 13:49
* Desc:用于监听recycleView的垂直滚动,然后将垂直滚动转发给其他类。
*
* //在provider中使用
* RVScrollHelper.create(binding.getRoot(), dy -> {
* binding.rvHotVideos.scrollBy(dy,0);
* return null;
* });
* </pre>
*/
public class RVScrollHelper implements View.OnAttachStateChangeListener {
TRSFunction<Integer, Void> scrollCallBack;
View child;
RecyclerView recyclerView;
private int recyclerViewHeight;
public static RVScrollHelper create(View child,TRSFunction<Integer, Void> scrollCallBack){
if(child==null){
return null;
}
Object tag = child.getTag(R.id.key_rv_scroll_helper);
if(!(tag instanceof RVScrollHelper)){
RVScrollHelper helper = new RVScrollHelper(child, scrollCallBack);
tag=helper;
child.setTag(R.id.key_rv_scroll_helper,helper);
}
return (RVScrollHelper) tag;
}
private RVScrollHelper(View child, TRSFunction<Integer, Void> scrollCallBack) {
this.scrollCallBack = scrollCallBack;
this.child = child;
this.child.addOnAttachStateChangeListener(this);
}
@Override
public void onViewAttachedToWindow(View v) {
if(child==null){
return;
}
if (recyclerView == null) {
recyclerView = getRecyclerView(v);
recyclerViewHeight = recyclerView.getHeight();
recyclerView.addOnScrollListener(onScrollListener);
}
}
@Override
public void onViewDetachedFromWindow(View v) {
if(recyclerView!=null) {
recyclerView.removeOnScrollListener(onScrollListener);
recyclerView=null;
}
}
private RecyclerView.OnScrollListener onScrollListener=new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//只有在view全部显示出来以后,才发送滚动事件
boolean isAllShow=isAllShow();
if(isAllShow){
if(scrollCallBack!=null){
scrollCallBack.call(dy);
}
}
}
};
private boolean isAllShow() {
int top = child.getTop();
int bottom = child.getBottom();
return bottom>=0&&bottom<=recyclerViewHeight;
}
private RecyclerView getRecyclerView(View v) {
ViewParent parent = v.getParent();
while (!(parent instanceof RecyclerView) && parent != null) {
parent = parent.getParent();
}
if(parent!=null){
return (RecyclerView) parent;
}
return null;
}
}
使用
在provider中使用。
RVScrollHelper.create(holder.itemView, dy -> {
recyclerView.scrollBy(dy, 0);
return null;
});