让一个ImageView在屏幕中来回运动
文章分类:移动开发
onCreate()中:
- iv=(ImageView) this .findViewById(R.id.iv);
- iv.setTag("toRight" );
- iv.setOnClickListener(listener);
- ani_0 = new TranslateAnimation(
- Animation.RELATIVE_TO_PARENT, 0 .0f, Animation.RELATIVE_TO_PARENT, - 1 .0f,
- Animation.RELATIVE_TO_SELF, 0 .0f, Animation.RELATIVE_TO_SELF, 0 .0f);
- ani_1= new TranslateAnimation(
- Animation.RELATIVE_TO_PARENT, -1 .0f, Animation.RELATIVE_TO_PARENT, 0 .0f,
- Animation.RELATIVE_TO_SELF, 0 .0f, Animation.RELATIVE_TO_SELF, 0 .0f);
- ani_0.setInterpolator(new AccelerateDecelerateInterpolator());
- ani_0.setDuration(1000 );
- ani_0.setFillEnabled(true );
- ani_0.setFillAfter(true );
- ani_0.setAnimationListener(animationListener);
- ani_1.setInterpolator(new AccelerateDecelerateInterpolator());
- ani_1.setDuration(1000 );
- ani_1.setFillEnabled(true );
- ani_1.setFillAfter(true );
- ani_1.setAnimationListener(animationListener);
点击Imageview启动动画:
- OnClickListener listener= new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- switch (v.getId()) {
- case R.id.iv:
- iv.startAnimation(ani_0);
- break ;
- }
- }
添加动画监听,在AnimationEnd的时候切换动画:
- final AnimationListener animationListener = new AnimationListener() {
- @Override
- public void onAnimationEnd(Animation animation) {
- if (animation == ani_0) {
- iv.startAnimation(ani_1);
- }
- if (animation == ani_1) {
- iv.startAnimation(ani_0);
- }
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onAnimationStart(Animation animation) {
- // TODO Auto-generated method stub
- }
- };
布局,让ImageView一开始的时候在屏幕右边:
- <? xml version = "1.0" encoding = "utf-8" ?>
- < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
- android:orientation = "vertical"
- android:layout_width = "fill_parent"
- android:layout_height = "fill_parent" >
- < ImageView android:id = "@+id/iv"
- android:layout_width = "wrap_content"
- android:layout_height = "wrap_content"
- android:src = "@drawable/search2"
- android:scaleType = "fitCenter"
- android:layout_gravity = "right"
- />
- </ LinearLayout >
本实例只是实现连续动画的一种简单办法,针对本例子应该还有更简单的方法.