转载请标明出处: http://blog.csdn.net/airsaid/article/details/53143754
本文出自:周游的博客
前言
由于 Android 的屏幕局限性,为了展示更多的东西,实现一个可以滑动的 View 还是非常重要的。所以这篇文章主要记下View的几种常见滑动方式:
- 通过 View 的 ScrollBy 和 ScrollTo 方法实现滑动。
- 通过动画给 View 施加位移效果来实现滑动。
- 通过改变 View 的 LayoutParams 使 View 重新布局从而实现滑动。
scrollBy()&scrollTo()
Android专门提供了scrollBy()和scrollTo()方法来实现View的滑动,而我们通过查看scrollBy()方法的源码可以发现,其方法内部其实同样调用的scrolllTo()方法:
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
那么两个方法之间又有什么区别和联系呢?一句话可以理解为:
- scrollBy()方法是基于当前位置的相对滑动。
- scrollTo()方法是基于所传递参数的绝对滑动。
通过查看源码我们知道,scrollBy()方法内部其实就是调用了scrollTo()方法,只不过参数中多加了mScrollX和mScrollY这两个变量,那么这2个变量究竟是什么呢?
mScrollX和mScrollY我们可以理解为View的偏移量,初始值都为0。当View发生移动时,比如说,View往左横向移动了100px,那么这时,mScrollX的值则为100。相反,如果是往右移动100px,那么此时值为-100。mScrollY则是如果往上垂直移动100px,mScrollY的值则为100,否则为-100。具体如下图所示:
(图片摘自:https://github.com/Idtk/Blog/blob/master/Blog/8%E3%80%81Scroll.md)
下面来写个Demo,演示下两者的区别和使用:
- 第一步:布局中定义好Layout,并且包裹好两个button
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.airsaid.viewdemo.MainActivity">
<Button
android:id="@+id/btn_scrollto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ScrollTo"/>
<Button
android:id="@+id/btn_scrollby"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ScrollBy"/>