美文网首页精选案例
NestedScrollView滑动到指定View的位置

NestedScrollView滑动到指定View的位置

作者: 俗人浮生 | 来源:发表于2019-03-20 20:00 被阅读178次

    那天遇到一个这样子的需求:类似于表单的提交,这表单有点长,需用NestedScrollView进行嵌套保证其能够滑动,提交表单的时候进行部分数据的校验,项目经理随便说了一嘴:如果哪项校验不通过就滑动到其对应的位置,这个要求好像有点高吧?

    我因为心里也没多大把握,所以不敢打包票,毕竟还涉及到Fragment嵌套其中,之前也没试过,但直觉告诉我应该是可以做到的,于是必须动手啊!还是先看看具体的布局结构图吧: 布局结构图.png
    在正式上代码前,我们先来看看两个测量的API:

    View.getLocationInWindow(int[] location):一个控件在其父窗口中的坐标位置
    View.getLocationOnScreen(int[] location):一个控件在其整个屏幕上的坐标位置
    很明显,在这个需求中,我们必须使用:getLocationOnScreen
    另外,还有一点需注意的,该需求要的是滑动到某个View的位置,而明显该布局是带Header的,所以必须算上NestedScrollView相对于屏幕的距离。
    还是直接上代码,首先我们在Activity中定义一个方法:

        private NestedScrollView nestedScrollView;
        private int nestedScrollViewTop;
       //控制nestedScrollView滑动到一定的距离
        public void scrollByDistance(int dy){
            if(nestedScrollViewTop==0){
                int[] intArray=new int[2];
                nestedScrollView.getLocationOnScreen(intArray);
                nestedScrollViewTop=intArray[1];
            }
            int distance=dy-nestedScrollViewTop;//必须算上nestedScrollView本身与屏幕的距离
            nestedScrollView.fling(distance);//添加上这句滑动才有效
            nestedScrollView.smoothScrollBy(0,distance);
        }
    

    上面的代码需注意两点:
    1、nestedScrollViewTop不能在activity创建之时就进行测量计算,因为界面未绘制完毕,无法测量出结果,如果你在创建时测量的话得出的结果一定是0,所以,只能像上面那样,调用时才进行测量计算。
    2、注意添加:nestedScrollView.fling(distance);这一句,否则会导致滑动无效。

    然后,我们再来看看Fragment中的代码:

      int[] intArray=new int[2];
      view.getLocationOnScreen(intArray);//测量某View相对于屏幕的距离
      MyActivity activity =(MyActivity) getActivity();
      activity.scrollByDistance(intArray[1]);
    

    好啦,大概也就这样,从上面代码也可以看出,其实整个实现也不是很复杂,所以,多尝试多动手很重要!

    相关文章

      网友评论

        本文标题:NestedScrollView滑动到指定View的位置

        本文链接:https://www.haomeiwen.com/subject/xfczpqtx.html