获取滚动UI的滚动距离

最近开发需要判断滚动视图视图是否滚动到底部,查了一下网上的方案,自己总结,记一下。

NestedScrollView监听滚动到底部

如果要判断滚动到底部,只要获取NestedScrollView的子View的高度来对比滚动的距离就好了。

final NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.view_scroll);
nestedScrollView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (motionEvent.getAction()){

            case MotionEvent.ACTION_MOVE:

                //滚动高度
                int scrollY = view.getScrollY();
                int height = view.getHeight();

                int firstChildViewHeight = nestedScrollView.getChildAt(0).getMeasuredHeight();

                //避免多次判断,只在刚滚动到底部的时候执行
                boolean tempScrollToBottom = Math.abs(scrollY + height - firstChildViewHeight) < 10;
                if (tempScrollToBottom != scrollTOBottom){
                    scrollTOBottom = tempScrollToBottom;
                    if (scrollTOBottom){
                        Log.e("TAG", "scrolled to bottom");
                    }
                }
                break;
        }
        return false;
    }
});

NestedScrollView监听滚动到某个子View

获取滚动视图的滚动内容,可以获取到子View后再获取到第二级的View高度来计算。

WebView监听滚动到底部

方法与NestedScrollView类似,但是在计算的时候需要添注意获取的View高度要乘上webVeiw的缩放比。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容