Android:View的滑动

View的滑动

可通过三种方式实现View的滑动:

  • 通过View本身提供的scrollTo、scrollBy方法来实现滑动
  • 通过动画给View施加平移效果来实现滑动
  • 通过改变View的LayoutParams使得View重新布局从而实现滑动

使用scrollTo、scrollBy

复制代码
public void scrollTo(int x,int y) {
    if (mScrollX != x || mScrollY != y) {
        int oldX = mScrollX;
        int oldY = mScrollY;
        mScrollX = x;
        mScrollY = y;
        invalidateParentCaches();
        onScrollChanged(mScrollX,mScrollY,oldX,oldY);
        if (!awakenScrollBars()) {
            postInvalidateOnAnimation();
        }
    }
}

public void scrollBy(int x,int y) {
    scrollTo(mScrollX + x,mScrollY + y);
}
  • scrollBy实际上也是调用了scrollTo方法,它是基于当前位置的相对滑动,而scrollTo则实现了基于所传递参数的绝对滑动

我们需要明白滑动过程中,View内部的两个属性mScrollX和mScrollY的改变规则

  1. 在滑动过程中,mScrollX的值总是等于View左边缘和View内容左边缘在水平方向的距离,而mScrollY的值总是等于View上边缘和View内容上边缘在竖直方向的距离
  2. scrollTo和scrollBy只能改变View内容的位置而不能改变View在布局中的位置
  3. 滑动时:从左向右滑动,mScrollX为负值,反之为正值、从上往下滑动,mScrollY为负值,反之为正值

使用动画

使用动画去实现滑动的效果,主要操作View的translationX和translationY属性,既可以采用传统的View动画,也可以采用属性动画(采用属性动画,需要采用开源库nineoldandroid)

  • 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="100" 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();

这两种方式实现的动画效果都是将一个View向右进行移动已达到想要的动画效果

注意:View动画时对View的影像做操作,并不能真正改变View的位置参数(包括宽/高);希望执行完动画的状态得以保持,需要将fillAfter属性设为true

改变布局参数

改变布局参数即改变LayoutParams,如想要把一个Button向右平移100px,我们可以将这个Button的LayoutParams里的marginLeft参数的值增加100px

复制代码
//重新设置一个View的LayoutParams

MarginLayoutParams params = (MarginLayoutParams)mButton1.getLayoutParams();
params.width += 100;
params.leftMargin += 100;
mButton1.requestLayout();

//或者mButton1.setLayoutParams(params)

上述滑动方式的对比

  • scrollTo/scrollBy:操作简单,适合对View内容的滑动
  • 动画:操作简单,适合用于没有交互的View的实现复杂的动画效果
  • 改变布局参数:操作稍微复杂,使用于有交互的View
相关推荐
雨声不在1 小时前
gradle编译missing_rules报错处理
android·gradle·agp8
Propeller3 小时前
【Kotlin】Kotlin 基础语法:变量、控制和函数
kotlin
用户7093722538513 小时前
配置vscode阅读Android native 代码
android
tangweiguo030519874 小时前
Android OpenGL ES 2.0 完整开发指南:从零到三维旋转立方体
android
龚礼鹏4 小时前
AndroidStudio module编译aar混淆文件处理
android
程序员阿鹏6 小时前
MySQL中给字段添加唯一约束的方式有哪些?
android·数据库·mysql
三少爷的鞋7 小时前
Android Data 层设计的四条红线:为什么必须坚持、如何落地
android
猫豆~8 小时前
zabbix实战——3day
android
知行合一。。。9 小时前
Python--01--核心基础
android·java·python
汤米粥9 小时前
Android简单易用的视频压缩
android