平移动画TranslateAnimation
以图片布局时位置为原点(0,0)平移
/**
*fromXDelta:动画开始X坐标
*toXDelta:动画结束 X坐标
*fromYDelta:动画开始Y坐标
*toYDelta:动画结束Y坐标
*/
new TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
//动画持续时间(ms)
TranslateAnimation.setDuration(2000);
//动画结束是否停在该位置,默认是false(回到原来位置)
TranslateAnimation.setFillAfter(true);
//开始动画
View.startAnimation(animation)
注意:
没有指定fromXType toXType fromYType toYType参数,默认以自身为参照物
举例说明
动画轨迹A -> B-> C
xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/topbar_select"/>
</LinearLayout>
> A为起始位置开始动画
A移动到B
/**
*
* 默认是以A坐标为参照坐标
*第一个参数0:动画开始x坐标
*第二个参数a:动画结束时x坐标
*第三个参数0:动画起始时y坐标
*第四个参数0:动画结束时y坐标
*/
Animation animation = new TranslateAnimation(0, a, 0, 0);
animation.setFillAfter(true);
animation.setDuration(300);
cursor.startAnimation(animation);
> B移动到C
/**
*
*默认是以自己(A的位置)为相对参照物
*第一个参数a:动画起始时x坐标,注意这里不是以B位置为参照,是以A位置为参照
*第二个参数b:动画结束时x坐标
*/
Animation animation2 = new TranslateAnimation(a, b + a, 0, 0);
> C移动到B
/**
*
*默认是以自己(A的位置)为相对参照物
*第一个参数b + a:动画起始时x坐标,注意这里不是以C位置为参照,是以A位置为参照
*第二个参数a:动画结束时x坐标
*/
Animation animation3 = new TranslateAnimation(b + a, a, 0, 0);
> C移动到A
/**
*
*默认是以自己(A的位置)为相对参照物
*第一个参数b + a:动画起始时x坐标,注意这里不是以C位置为参照,是以A位置为参照
*第二个参数0:动画结束时x坐标
*/
Animation animation4 = new TranslateAnimation(b + a, 0, 0, 0);
/**
*B -> A
*默认是以自己(A的位置)为相对参照物
*第一个参数b:动画起始时x坐标,注意这里不是以B位置为参照,是以A位置为参照
*第二个参数0:动画结束时x坐标
*/
Animation animation5 = new TranslateAnimation(b, 0, 0, 0);
/**
*A -> C
*默认是以自己(A的位置)为相对参照物
*第一个参数0:动画起始时x坐标
*第二个参数a +b:动画结束时x坐标
*/
Animation animation6 = new TranslateAnimation(0, a + b, 0, 0);
- 改变参照物
以B为参照物
修改xml布局,ImageView宽度为a
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="adp"
android:layout_height="wrap_content"
android:src="@drawable/topbar_select" />
</LinearLayout>
修改图片的初始化位置,这里是修改ImageView前景图片
Matrix matrix = new Matrix();
matrix.postTranslate(a, 0);
ImageView.setImageMatrix(matrix);