安卓实现掘金 APP 首页滑动吸顶效果

先上最终效果

1657521886191.gif

使用的组件 TabLayout ViewPager NestScrollView RecyclerView

主要实现

首先我们要自定义一个我 ScrollView 继承自 NestedScrollView,重写 onMeasure 方法,在这个方法中我们获取 scrollview 可以滚动的最大距离,再重新 onNestedPreScroll 方法,在这里面去判断是否先消费子级的滚动。下面是主要代码展示

public class MyScrollView extends NestedScrollView {

    private final String TAG = "MyScrollView";

    private int maxScrollHeight;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //获取scrollView 最大可滚动的距离
        maxScrollHeight = this.getChildAt(0).getMeasuredHeight() - this.getMeasuredHeight();
    }


    @Override
    public void onNestedPreScroll(@NonNull View target, int dx, int dy, @NonNull int[] consumed,
                                  int type) {

        super.onNestedPreScroll(target, dx, dy, consumed, type);

        //如果最大可滚动距离大于 0 则表示 scrollview 可以滚动,则去先消费用户滑动
        if(this.maxScrollHeight > 0){
            //判断用户是否是向上滑动,并且没有超出 scrollview 可滑动的最大距离
            boolean headerScrollUp = dy > 0 && getScrollY() < this.maxScrollHeight;

            //判断用户是否是向下滑动,并且没有超出可滑动距离
            boolean headerScrollDown = dy < 0 && getScrollY() > 0;

            //如果 scrollview 可以滑动,则去消费滑动
            if (headerScrollUp || headerScrollDown) {
                scrollBy(0, dy);
                consumed[1] = dy;
            }
            //通知子列表,父级消费的距离
            this.dispatchNestedPreScroll(dx, dy, consumed, null, type);
        }
    }
}
复制代码

接着我们需要将 tab view 的内容高的设置为整个屏幕高度,这样我们在往上滚动的时候,最后就会只剩下 tab 的内容。下面是主要代码展示。

//动态设置外层布局的高度,让整个 tab 页为屏幕高度
LinearLayout linearLayout = this.findViewById(R.id.linearLayout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
linearLayout.setLayoutParams(layoutParams);
复制代码

最后附上完整代码地址代码

猜你喜欢

转载自juejin.im/post/7119007162965164040