View事件体系 -- 滑动

一、使用scrollTo / scrollBy

scrollTo / scrollBy 只能改变View内容的位置,而不能改变View在布局中的位置。
scrollTo:基于所传递参数的绝对滑动。

public void scrollTo(int x, int y)

例子:

//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/main_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

//代码
mMain_layout = (RelativeLayout)findViewById(R.id.main_layout);
mMain_layout.scrollTo(-+500, -+500); //注意负数前面要加"-+"

scrollBy:基于当前位置的相对滑动。

public void scrollBy(int x, int y) {
    scrollTo(mScrollX + x, mScrollY + y);
}

例子:

//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/main_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

//代码
mMain_layout = (RelativeLayout)findViewById(R.id.main_layout);
mMain_layout.scrollTo(-+100, 0); //注意负数前面要加"-+"
mMain_layout.scrollBy(-+400, -+500); //注意负数前面要加"-+"

View内部有两个滑动相关的属性:mScrollX和mScrollY。
mScrollX:通过getScrollX()获取,表示View左边缘和View内容左边缘在水平方向的距离。当View左边缘在View内容左边缘的右边时为正值(从右向左滑动),反之为负值(从左向右滑动)。
mScrollY:通过getScrollY()获取,表示View上边缘和View内容上边缘在竖直方向的距离。当View上边缘在View内容上边缘的下边时为正值(从下向上滑动),反之为负值(从上向下滑动)。

二、使用动画

使用动画来移动View,主要是操作View的translationX和translationY属性,既可以采用传统的View动画,也可以采用属性动画。
使用方法及工作原理将在"动画"小节介绍。
例子:
View动画:

<?xml version="1.0" encoding="utf-8"?>   
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:zAdjustment="normal">  
    <translate   
        android:duration="1000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXDelta="100"
        android:toYDelta="100" />   
</set>   

属性动画:

ObjectAnimator.ofFloat(targetView, "translationX", 0, 100).setDuration(100).start();

三、改变布局参数

改变布局参数即改变LayoutParams。
例子:

MarginLayoutParams params = (MarginLayoutParams)mButton1.getLayoutParams();
params.width += 100;
params.leftMargin += 100;
mButton1.requestLayout();
//或者 mButton1.setLayoutParams(params);

四、各种滑动方式的对比

scrollTo / scrollBy:操作简单,适合对View内容的滑动。
动画:主要适用于没有交互的View和实现复杂的动画效果。
改变布局参数:操作稍微复杂,适用于有交互的View。

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

推荐阅读更多精彩内容