0%
这是一片思考的空间 -- arthinking
Spring 重构&代码整洁之道 软件设计 JVM 并发编程 数据结构与算法 分布式 存储 网络 微服务 设计模式
Java技术栈 - 涉及Java技术体系

Android中使用Animation实现控件的动画效果以及Interpolator和AnimationListener的使用

Animation的4个基本动画效果

What is Animation?

public abstract class Animation extends Object implements Cloneable

Abstraction for an Animation that can be applied to Views, Surfaces, or other objects.

1、AlphaAnimation:淡入淡出效果

public class AlphaAnimation extends Animation

An animation that controls the alpha level of an object. Useful for fading things in and out. This animation ends up changing the alpha property of aTransformation

Public Constructors AlphaAnimation(Context context, AttributeSet attrs) Constructor used when an AlphaAnimation is loaded from a resource. AlphaAnimation(float fromAlpha, float toAlpha) Constructor to use when building an AlphaAnimation from code

public class AnimationSet extends Animation

Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values. 在代码中实现动画效果的方法:

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
AnimationSet animationSet = new AnimationSet(true);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(1000);
alphaAnimation.setStartOffset(10000);
animationSet.addAnimation(alphaAnimation);
//animationSet.setStartOffset(10000);
animationSet.setFillBefore(false);
animationSet.setFillAfter(true);
imageView.startAnimation(animationSet);

在XML文件中实现动画效果的方法: ① 在res目录下创建一个anim文件夹,在里面添加一个alpha.xml文件:


② 在Activity中使用AnimationUtils获取Animation并进行设置:

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alpha);
imageView.startAnimation(animation);

2、ScaleAnimation:缩放效果

public class ScaleAnimation extends Animation

An animation that controls the scale of an object. You can specify the point to use for the center of scaling.

Public Constructors ScaleAnimation(Context context, AttributeSet attrs) Constructor used when a ScaleAnimation is loaded from a resource. ScaleAnimation(float fromX, float toX, float fromY, float toY) Constructor to use when building a ScaleAnimation from code ScaleAnimation(float fromX, float toX, float fromY, float toY, float pivotX, float pivotY) Constructor to use when building a ScaleAnimation from code ScaleAnimation(float fromX, float toX, float fromY, float toY, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue) Constructor to use when building a ScaleAnimation from code

在代码中实现动画效果:

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
AnimationSet animationSet = new AnimationSet(true);
ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f,
Animation.RELATIVE_TO_SELF, 1f,
Animation.RELATIVE_TO_SELF, 1f);
animationSet.addAnimation(scaleAnimation);
animationSet.setDuration(1000);
imageView.startAnimation(animationSet);

在XML文件中实现动画效果的方法: ① 在res的anim文件夹下,创建一个scale.xml文件:

<scale android:fromXScale="1.0"
	android:toXScale="0.0"
	android:fromYScale="1.0"
	android:toYScale="0.0"
	android:pivotX="50%"
	android:pivotY="50%"
	android:duration="2000" />

② 在Activity中使用AnimationUtils获取Animation并进行设置:

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale);
imageView.startAnimation(animation);

3、Rotate:旋转效果

public class RotateAnimation extends Animation

An animation that controls the rotation of an object. This rotation takes place int the X-Y plane. You can specify the point to use for the center of the rotation, where (0,0) is the top left point. If not specified, (0,0) is the default rotation point.

Public Constructors RotateAnimation(Context context, AttributeSet attrs) Constructor used when a RotateAnimation is loaded from a resource. RotateAnimation(float fromDegrees, float toDegrees) Constructor to use when building a RotateAnimation from code. RotateAnimation(float fromDegrees, float toDegrees, float pivotX, float pivotY) Constructor to use when building a RotateAnimation from code RotateAnimation(float fromDegrees, float toDegrees, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue) Constructor to use when building a RotateAnimation from code

在代码中实现动画效果:

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
AnimationSet animationSet = new AnimationSet(true);
RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_PARENT, 0.5f,
Animation.RELATIVE_TO_PARENT, 0.5f);
rotateAnimation.setDuration(1000);
animationSet.addAnimation(rotateAnimation);
imageView.startAnimation(animationSet);

在XML文件中实现动画效果的方法: ① 在res的anim文件夹下,创建一个rotate.xml文件:

<rotate android:fromDegrees="0"
	android:toDegrees="+360"
	android:pivotX="50%"
	android:pivotY="50%"
	android:duration="1000" />

② 在Activity中使用AnimationUtils获取Animation并进行设置:

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
imageView.startAnimation(animation);

4、 Translate:移动效果

public class TranslateAnimation extends Animation

An animation that controls the position of an object.

Public Constructors TranslateAnimation(Context context, AttributeSet attrs) Constructor used when a TranslateAnimation is loaded from a resource. TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) Constructor to use when building a TranslateAnimation from code TranslateAnimation(int fromXType, float fromXValue, int toXType, float toXValue, int fromYType, float fromYValue, int toYType, float toYValue) Constructor to use when building a TranslateAnimation from code

在代码中实现动画效果:

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
AnimationSet animationSet = new AnimationSet(true);
TranslateAnimation translateAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 1.0f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 1.0f);
translateAnimation.setDuration(1000);
animationSet.addAnimation(translateAnimation);
imageView.startAnimation(animationSet);

在XML文件中实现动画效果的方法: ① 在res的anim文件夹下,创建一个translate.xml文件:

<translate
	android:fromXDelta="0%p"
	android:toXDelta="100%p"
	android:fromYDelta="0%p"
	android:toYDelta="100%p"
	android:duration="1000" />

其中100%p表示相对于父空间的位置 ② 在Activity中使用AnimationUtils获取Animation并进行设置:

Animation animation = (Animation) AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
imageView.startAnimation(animation);

也可以使用AnimationSet为一个控件添加多个动画,或者在xml文件中添加多个动画标签,以下分别使用代码和XML文件实现相同的效果:

代码中实现:

AnimationSet animationSet = new AnimationSet(false);
AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);
ScaleAnimation scale = new ScaleAnimation(1, 0.5f, 1, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
animationSet.addAnimation(alpha);
animationSet.addAnimation(scale);
animationSet.setDuration(2000);
animationSet.setStartOffset(1000);
animationSet.setFillAfter(true);
imageView.startAnimation(animationSet);

XML实现:

alpha.xml

<alpha
	android:fromAlpha="1.0"
	android:toAlpha="0.0"
	android:startOffset="1000"
	android:fillAfter="true"
	android:duration="2000" />

<scale android:fromXScale="1.0"
	android:toXScale="0.5"
	android:fromYScale="1.0"
	android:toYScale="0.5"
	android:pivotX="50%"
	android:pivotY="50%"
	android:startOffset="1000"
	android:duration="2000" />

Activity中的代码:

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alpha);
imageView.startAnimation(animation);

Interpolator的使用

什么是Interpolator

public class Interpolator extends Object

Interpolator定义了动画变化的速率或规律,其具体的实现可以使用以下子类:

AccelerateDecelerateInterpolator:

public class AccelerateDecelerateInterpolator extends Object implements Interpolator

An interpolator where the rate of change starts and ends slowly but accelerates through the middle. AccelerateInterpolater:

public class AccelerateInterpolator extends Object implements Interpolator

An interpolator where the rate of change starts out slowly and and then accelerates. CycleInterpolator:

public class CycleInterpolator extends Object implements Interpolator

Repeats the animation for a specified number of cycles. The rate of change follows a sinusoidal pattern. DecelerateInterpolator:

public class DecelerateInterpolator extends Object implements Interpolator

An interpolator where the rate of change starts out quickly and and then decelerates. LinearInterpolator:

public class LinearInterpolator extends Object implements Interpolator

An interpolator where the rate of change is constant.

这些Interpolator可以在代码或XML文件中定义:

XML文件定义在set标签里或每个动画标签 set标签中定义:

每个动画标签中定义:


<scale
	android:interpolator="@android:anim/accelerate_decelerate_interpolator"
	android:fromXScale="1.0"
	android:toXScale="0.5"
	android:fromYScale="1.0"
	android:toYScale="0.5"
	android:pivotX="50%"
	android:pivotY="50%"
	android:startOffset="1000"
	android:duration="2000" />

在代码中设置:

AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new AccelerateInterpolator());

或者分别为每个动画设置:

AnimationSet animationSet = new AnimationSet(false);
AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);
alpha.setInterpolator(new AccelerateInterpolator());
ScaleAnimation scale = new ScaleAnimation(1, 0.5f, 1, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scale.setInterpolator(new AccelerateDecelerateInterpolator());

Frame-By-Frame Animations的使用

① 准备4张图片run1.png,run2.png,run3.png,run4.png分别放到res的三个drawable文件夹中 ② 在res的drawable-ldpi目录下创建一个anim_run.xml文件:






③ 在Activity中使用xml文件设置ImageView控件imageView的背景源,并获取AnimationDrawable进行显示动画:

imageView.setBackgroundResource(R.drawable.anim_run);
AnimationDrawable animationDrawable = (AnimationDrawable)imageView.getBackground();
animationDrawable.start();

使用LayoutAnimationController设置ListView的动画

什么是LayoutAnimationController?

public class LayoutAnimationController extends Object

A layout animation controller is used to animated a layout's, or a view group's, children. Each child uses the same animation but for every one of them, the animation starts at a different time. A layout animation controller is used by ViewGroup to compute the delay by which each child's animation start must be offset. The delay is computed by using characteristics of each child, like its index in the view group. This standard implementation computes the delay by multiplying a fixed amount of miliseconds by the index of the child in its parent view group. Subclasses are supposed to override getDelayForView(android.view.View) to implement a different way of computing the delay. For instance, aGridLayoutAnimationController will compute the delay based on the column and row indices of the child in its parent view group. Information used to compute the animation delay of each child are stored in an instance of LayoutAnimationController.AnimationParameters, itself stored in theViewGroup.LayoutParams of the view. 在使用LayoutAnimationController控制ListView控件的样式效果的方法: ① 在res的anim文件夹中创建一个list_anim.xml文件用于控制ListView控件的动画:

<scale android:fromXScale="0.0"
	android:toXScale="1.0"
	android:fromYScale="0.0"
	android:toYScale="1.0"
	android:pivotX="50%"
	android:pivotY="50%"
	android:duration="1000" />

② 创建一个布局文件item.xml用于设置ListView的item的样式:




③ 在主Activity的布局文件main.xml中添加一个ListView

④ 创建一个MainActivity继承ListActivity,并在onCreate方法中添加如下代码:

ListView listView = getListView();

List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("user_name", "arthinking");
hm1.put("user_id", "001");
HashMap<String, String> hm2 = new HashMap<String, String>();
hm2.put("user_name", "Jason");
hm2.put("user_id", "002");
list.add(hm1);
list.add(hm2);

SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
R.layout.item, new String[] { "user_name", "user_id" },
new int[] { R.id.user_name, R.id.user_id });
listView.setAdapter(simpleAdapter);

//通过Animation获取LayoutAnimationController对ListView进行设置
Animation animation = (Animation)AnimationUtils.loadAnimation(MainActivity.this, R.anim.list_anim);
LayoutAnimationController lac = new LayoutAnimationController(animation);
lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
lac.setDelay(0.5f);
listView.setLayoutAnimation(lac);

这样,运行程序,显示的ListView就会按照xml文件中预置的动画效果显示了。 也可以通过xml文件进行设置动画: ① 在以上步骤的基础之上,在res/anim文件夹下创建一个anim_layout.xml文件:

② main在布局文件的的ListView添加如下属性:

android:layoutAnimation="@anim/anim_layout"

这样就在把MainActivity的onCreate()方法中的 //通过Animation获取LayoutAnimationController对ListView进行设置 注释后的代码删除了,直接使用xml进行动画的控制。

AnimationListener的使用

public static interface Animation.AnimationListener android.view.animation.Animation.AnimationListener

An animation listener receives notifications from an animation. Notifications indicate animation related events, such as the end or the repetition of the animation. 包含以下的三个方法:

onAnimationEnd(Animation animation) Notifies the end of the animation. onAnimationRepeat(Animation animation) Notifies the repetition of the animation. onAnimationStart(Animation animation) Notifies the start of the animation.

AnimationListener在控件中的使用:

① 可以为一个Button添加一个事件:

button.setOnClickListener(new TestAnimationListener());

② 接下来是编写这个TestAnimationListener类,继承AnimationListener,并覆盖里面的三个方法:

//这里获取控件组,R.id.layoutId为main.xml的整体布局标签的id属性值
ViewGroup viewGroup = (ViewGroup)findViewById(R.id.layoutId);

private class RemoveAnimationListener implements AnimationListener{
//该方法在淡出效果执行结束之后被调用
@Override
public void onAnimationEnd(Animation animation) {
//假设这里要在动画执行完之后删除一个TextView
viewGroup.removeView(textView);
}

@Override
public void onAnimationRepeat(Animation animation) {
	System.out.println("onAnimationRepeat");
}

@Override
public void onAnimationStart(Animation animation) {
	System.out.println("onAnimationStart");
}

}

③ 同样的,在动画效果中添加控件可以按照如下实现

ScaleAnimation scale = new ScaleAnimation(1, 0.5f, 1, 0.5f,
scale.setDuration(1000);
scale.setStartOffset(100);
TextView textView = new TextView(MainActivity.this);
textView.setText("add");
viewGroup.addView(textView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.startAnimation(scale);

(特别说明:本文部分内容是在观看marschen的Android视频教程时做的笔记,感谢marschen推出的视频教程,这里也推荐给大家:http://www.marschen.com/portal.php)

欢迎关注我的其它发布渠道

订阅IT宅
内功修炼
Java技术栈
Java架构杂谈是IT宅精品文章公众号,欢迎订阅:
📄 网络基础知识:两万字长文50+张趣图带你领悟网络编程的内功心法 📄 HTTP发展史:三万长文50+趣图带你领悟web编程的内功心法 📄 HTTP/1.1:可扩展,可靠性,请求应答,无状态,明文传输 📄 HTTP/1.1报文详解:Method,URI,URL,消息头,消息体,状态行 📄 HTTP常用请求头大揭秘 📄 HTTPS:网络安全攻坚战 📄 HTTP/2:网络安全传输的快车道 📄 HTTP/3:让传输效率再一次起飞 📄 高性能网络编程:图解Socket核心内幕以及五大IO模型 📄 高性能网络编程:三分钟短文快速了解信号驱动式IO 📄 高性能网络编程:彻底弄懂IO复用 - IO处理杀手锏,带您深入了解select,poll,epoll 📄 高性能网络编程:异步IO:新时代的IO处理利器 📄 高性能网络编程:网络编程范式 - 高性能服务器就这么回事 📄 高性能网络编程:性能追击 - 万字长文30+图揭秘8大主流服务器程序线程模型
📄 Java内存模型:如果有人给你撕逼Java内存模型,就把这些问题甩给他 📄 一文带你彻底理解同步和锁的本质(干货) 📄 AQS与并发包中锁的通用实现 📄 ReentrantLock介绍与使用 📄 ReentrantReadWriteLock介绍与使用 📄 ReentrantLock的Condition原理解析 📄 如何优雅的中断线程 📄 如何优雅的挂起线程 📄 图解几个好玩的并发辅助工具类 📄 图解BlockingQueue阻塞队列
📄 消息队列那么多,为什么建议深入了解下RabbitMQ? 📄 高并发异步解耦利器:RocketMQ究竟强在哪里? 📄 Kafka必知必会18问:30+图带您看透Kafka
📄 洞悉MySQL底层架构:游走在缓冲与磁盘之间 📄 SQL运行内幕:从执行原理看调优的本质 📄 洞悉Redis技术内幕:缓存,数据结构,并发,集群与算法