android ScrollByScrollTo以及平移动画以及重新LayoutParams的区别

来源:互联网 发布:汇率软件 编辑:程序博客网 时间:2024/05/22 01:50

1. 前言

view的滑动在安卓中特别多,基本有三种方式:

1.通过view本身提供的scrollTo/scrollBy方法实现滑动。
2.通过给view添加平移动画实现滑动。
3.通过改变view的layoutparams使得view重新布局,从而实现滑动。

2.使用方法

(1)通过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();            }        }    }
scrollTo调用public void scrollBy(int x, int y) {        scrollTo(mScrollX + x, mScrollY + y);    }

调用代码:

 linear_layout.scrollTo(200, 0);linear_layout.scrollBy(200, 0);

解析:
scrollTo:
实现view的滑动,基于当前位置的绝对滑动,x为正数,向左滑动x像素,通过源码可以知道,多次调用scrollTo并不会多次滑动,因为他会判断mScrollX != x || mScrollY != y,相等则不滑动。

scrollBy:
实现view的滑动,基于当前位置的相对滑动,x为正数,向左滑动x像素,通过源码可以知道,多次调用scrollBy会一直滑动,因为他会先调用mScrollX + x, mScrollY + y。
还有一个需要注意,这两个方法,只能改变view的内容,而不能改变view在布局中的位置,如果想改变view的布局中的位置,可以移动他的父布局。
(2).通过给view添加平移动画实现滑动
可以使用tween动画,当然也可以使用属性动画,我们这边先介绍平移动画。

//动画xml设置<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"     android:fillAfter="true">    <translate        android:duration="@android:integer/config_mediumAnimTime"        android:fromXDelta="0"        android:fromYDelta="0"        android:toXDelta="100"        android:toYDelta="0"/></set>//动画调用 Animation animation = AnimationUtils.loadAnimation(this,R.anim.slide_out_right); bitmap.startAnimation(animation);

解析:
平移动画,需要指出一个问题,平移动画不能真正改变view的位置,也就是说,一个view向左平移了100px,但是这个view的点击事件,并没有在新位置,而是在原始没有移动的那个位置,这个就比较尴尬了,平移后,点击事件没有办法触发。当
然有两个解决方案:1.用属性动画。2.预先设置一个一模一样的view在目标位置,点击事件处理跟外观跟移动的view都是一样,当目前的view移动后,立即隐藏,把预先设置的view显现,这样可以解决。

(3)通过改变view的layoutparams使得view重新布局,从而实现滑动。

 LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)bitmap.getLayoutParams();                linearParams.leftMargin +=100;                bitmap.setLayoutParams(linearParams);

解析:
这个比较简单,通过改变view的leftMargin ,rightMargin,达到移动的目的。
3.三种方式比较
1.scrollTo/scrollBy:操作简单,适合对view的内容的滑动,同样也可以对view的父元素滑动,从而让子元素位置改变。
2平移动画实现滑动:操作简单,适用于没有交互的view和有复杂动画效果的。
3.改变view的layoutparams使得view重新布局,从而实现滑动:操作复杂,适用于有交互的view。

0 0
原创粉丝点击