美文网首页
ScrollView 使用小结(滑动顶部/底部,吸顶,底部加载,

ScrollView 使用小结(滑动顶部/底部,吸顶,底部加载,

作者: 葛糖糖 | 来源:发表于2017-06-19 10:38 被阅读0次

    忙忙碌碌的一个多月又结束了,连续奋战到凌晨四点的两周也成为了过去式....此次上线因为添加了视频直播和点播功能,所以比较赶,真是分分钟要猝死的赶脚.不过此次又是上线又是对旧知识的巩固和对新技术的探究,此次用到的ScrollView比较多,写一篇文章用以积累.


    从谷歌的文档我们可以得到ScrollView是一个可以滚动的用户布局容器,它可以让在手机屏幕上展示不开的情况下滚动展示。ScrollView是一个FrameLayout,所以你应该把一个子控件包含在它的整个内容滚动;这个子控件本身可以是一个复杂的层次结构对象的布局管理器,这个子控件一般是在垂直方向的一个LinearLayout呈现,用户可以通过滚动的顶级项目的垂直阵列。如果一个ScrollView有多个布局就会报出以下的错误:


    error

    当然,也可以通过below和above让Scrollview在哪两个控件之间滚动,根据自己的项目实时调整.

    xml中常用到的属性:

    android:fadingEdge="none"

    设置拉滚动条时 ,边框渐变的方向。none(边框颜色不变),horizontal(水平方向颜色变淡),vertical(垂直方向颜色变淡).

    android:overScrollMode="never"

    删除ScrollView拉到尽头(顶部、底部),然后继续拉出现的阴影效果,适用于2.3及以上的 否则不用设置.

    android:scrollbars="none"

    设置滚动条显示。none(隐藏),horizontal(水平),vertical(垂直)。见下列代码演示使用该属性让EditText内有滚动条。但是其他容器如LinearLayout设置了但是没有效果。

    android:descendantFocusability=""

    该属性是当一个为view获取焦点时,定义viewGroup和其子控件两者之间的关系。
    属性的值有三种:

    beforeDescendants:viewgroup会优先其子类控件而获取到焦点
    afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
    blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
    

    ScrollView本身的高度设置为match_parent,其子View的高度也设置为match_parent,自然状态下该子View的高度并不会占满ScrollView的高度。 原因是match_parent针对一般布局而言,是子view的高度和parent的高度一致,但在ScrollView身上,工作机制并非如此,而是ScrollView的高度随着子View的高度变化而变化(子View高度大于ScrollView时)。在子View高度小于ScrollView高度时,必需在xml里为ScrollView加上Android:fillViewport="true",这样子View小于ScrollView高度时就会占满父View.
    解决方法:xml里为ScrollView加上android:fillViewport=“true".

    ScrollView 中常用到的方法:

    Scrollview禁止滑动:`
      scrollView.setOnTouchListener(new View.OnTouchListener() {
             @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                    return true;
            }});
    
    可滑动
       scrollView.setOnTouchListener(new View.OnTouchListener() {
              @Override
              public boolean onTouch(View view, MotionEvent motionEvent) {
                    return false;
              }});
    
    滚到到底部:
      scrollView.post(new Runnable() {
             @Override
              public void run() {
                     //滑动底部
                     scrollView.fullScroll(ScrollView.FOCUS_DOWN);
               }});
    
    滚动到顶部:
        scrollView.post(new Runnable() {
               @Override
                public void run() {
                    //滑动顶部
                    scrollView.fullScroll(ScrollView.FOCUS_UP);
               }});
    
    滚动到某个位置:
         scrollView.post(new Runnable() {
                @Override
                 public void run() {
                     int offset = 100;//偏移值
                     scrollView.smoothScrollTo(0, offset);
                 }});
    

    注意:ScrollView 滚动的时候需要post 一个runnable,让其在消息队列中执行滚动!
    第一,handler.post(runnable);并不是新开线程,只是让UI主线程去并发执行run()方法。
    第二,之所以放在handler里,是为了保证View都已经绘制完成。不然,你放在resume()中执行,应该也可以的。
    第三,smoothScrollTo类似于scrollTo,但是滚动的时候是平缓的而不是立即滚动到某处。另外,smoothScrollTo()方法可以打断滑动动画。

    监听ScrollView滑动到底部,加载数据:

    有时候我们想让在ScrollView滑动到底部的时候去做一些事情,但是scrollview并没有直接提供这样的方法,此时我们可以通过简单的继承一下ScrollView,为ScrollView滑动到底部设置一下监听:

    public class ScrollBottomScrollView extends ScrollView {
    
    private OnScrollBottomListener listener;
    private int calCount;
    
    public interface OnScrollBottomListener {
        void scrollToBottom();
    }
    
    public void onScrollViewScrollToBottom(OnScrollBottomListener l) {
        listener = l;
    }
    
    public void unRegisterOnScrollViewScrollToBottom() {
        listener = null;
    }
    
    public ScrollBottomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        View view = this.getChildAt(0);
        if (this.getHeight() + this.getScrollY() == view.getHeight()) {
            calCount++;
            if (calCount == 1) {
                if (listener != null) {
                    listener.scrollToBottom();
                }
            }
        } else {
            calCount = 0;
        }
    }
    }
    

    在需要的地方调用如下:

       scrollView.onScrollViewScrollToBottom(new ScrollBottomScrollView.OnScrollBottomListener() {
            @Override
            public void scrollToBottom() {
                  //请求数据
            }});
    

    另外如果你的布局中是ScrollView嵌入RecycerView那么久势必就会出现滑动冲突的问题,此时我们可以把RecycerView的滑动监听给禁止,这样就不会有冲突的问题了.

      LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
        //禁止recycleview竖直滑动
        @Overridepublic boolean canScrollVertically() {
              return false;
        }};
    

    大概就用到了这么多,以后有新的研究还会继续更新.
    2019.4.9更新

    scrollView 嵌套 RecyclerView 显示时会滚动到RecyclerView第一项

    recyclerView自动获取了焦点
    解决:
    1.recyclerView去除焦点

    recyclerview.setFocusableInTouchMode(false);
    recyclerview.requestFocus();
    

    2.让scrollView 或者 recyclerView顶端的某个控件获取焦点

    ll_top.setFocusableInTouchMode(true);  
    ll_top.requestFocus(); 
    

    ScrollView.setOnScrollChangeListener() API23以上可用问题

    1.创建一个接口将ScrollView的滑动方法暴露出来,在页面中进行监听

    class ScrollBottomScrollView @JvmOverloads constructor(
        context: Context,
        attributeSet: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : NestedScrollView(context, attributeSet, defStyleAttr) {
    
    private var scrollListener: OnScrollChangeListener? = null
    
    interface OnScrollChangeListener {
        fun onMScrollChanged(y: Int)
    }
    
    fun onScrollChangeListener(l: OnScrollChangeListener) {
        scrollListener = l
    }
    
    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        if (scrollListener != null) {
            scrollListener!!.onMScrollChanged(t)
        }
    }
    

    }
    2.在页面中调用

     scroll_view.onScrollChangeListener(object :ScrollBottomScrollView.OnScrollChangeListener{
            override fun onMScrollChanged(y: Int) {
               
            }
        })
    

    Scrollview 滚动某个位置使某个布局吸顶

    原理很简单,想要Scrollview在滑动过程中,某个部分吸顶,可以写一个相同布局的layout并隐藏,然后在scrollview滚动的时候监听滚动到哪个位置让隐藏的layout展示出来.
    show me code :

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <LinearLayout
            android:id="@+id/ll_top"
            android:layout_width="match_parent"
            android:layout_height="74dp"
            android:background="@drawable/shape_black_blue_gradient">     
        </LinearLayout>
    
        <com.sentiment.tigerobo.tigerobobaselib.component.viewgroup.ScrollBottomScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/ll_top"
            android:descendantFocusability="beforeDescendants"
            android:fillViewport="true"
            android:overScrollMode="never"
            android:scrollbars="none">
    
            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    
                <View
                    android:id="@+id/v_report_divider"
                    android:layout_width="match_parent"
                    android:layout_height="10dp"
                    android:background="@color/color_F2F2F2"
                    app:layout_constraintTop_toBottomOf="@+id/layout_ipo" />
    
                <include
                    android:id="@+id/layout_tab"
                    layout="@layout/layout_company_tab_display"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
    
            </android.support.constraint.ConstraintLayout>
        </com.sentiment.tigerobo.tigerobobaselib.component.viewgroup.ScrollBottomScrollView>
    
        <include
            android:id="@+id/layout_hide_tab"
            layout="@layout/layout_company_tab_hide"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ll_top"
            android:visibility="gone" />
    </RelativeLayout>
    

    吸顶逻辑控制

     scroll_view.onScrollChangeListener(object :ScrollBottomScrollView.OnScrollChangeListener{
            override fun onMScrollChanged(y: Int) {
                if (y > v_report_divider.bottom) {//滑动距离大于v_report_divider的底坐标
                    layout_hide_tab.visibility = View.VISIBLE
                } else {
                    layout_hide_tab.visibility = View.GONE
                }
            }
        })
    

    好吧 确实有点简单~~
    2019.10.14更新

    ScrollView的滑动跟静止监听

    在业务需求中,有时会遇到需要监听ScrollView实现页面的一些业务效果
    主要思路:创建Handler,在ScrollView滑动的时候,先清空所有消息,然后发送延时消息,如果能接收到消息,说明滑动停止,下面是具体实现的代码

    public class ObservableScrollView extends NestedScrollView {
    
      private OnScrollStatusListener onScrollStatusListener;
    
      public ObservableScrollView(Context context) {
        super(context);
      }
    
      public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
      }
    
      @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (onScrollStatusListener != null) {
          onScrollStatusListener.onScrolling();
          mHandler.removeCallbacksAndMessages(null);
          mHandler.sendEmptyMessageDelayed(0x01, 200);
        }
      }
    
      public void setOnScrollStatusListener(OnScrollStatusListener onScrollStatusListener) {
        this.onScrollStatusListener = onScrollStatusListener;
      }
    
      private Handler mHandler = new Handler() {
    
        @Override public void handleMessage(Message msg) {
          super.handleMessage(msg);
          switch (msg.what) {
            case 0x01:
              if (onScrollStatusListener != null) {
                onScrollStatusListener.onScrollStop();
              }
              break;
          }
        }
      };
    
      @Override protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mHandler.removeCallbacksAndMessages(null);
      }
    
      public interface OnScrollStatusListener {
        void onScrollStop();
    
        void onScrolling();
      }
    }
    

    然后在代码中

    ObservableScrollView scrollView = findViewById(R.id.scrollView);
        final TextView tvTest = findViewById(R.id.tv_test);
        scrollView.setOnScrollStatusListener(new ObservableScrollView.OnScrollStatusListener() {
          @Override public void onScrollStop() {
            tvTest.setText("停止滑动");
          }
    
          @Override public void onScrolling() {
            tvTest.setText("滑动中");
          }
        });
    

    可以监听到ScrollView的滑动跟静止状态变化。
    谷歌官方文档https://developer.android.com/reference/android/widget/ScrollView.html

    相关文章

      网友评论

          本文标题:ScrollView 使用小结(滑动顶部/底部,吸顶,底部加载,

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