Android动画之二:View Animation

作为一个博客《Android其中的动画:Drawable Animation》。android动画主要分为三大部分。上一篇博客已经解说Drawable Animation的使用方法,即逐帧地显示图片,常常运用于动态显示一个进度动画,这是出现频率最高的应用场景。接下来。我们这篇文章将循序渐进。介绍View Animation。

View Animation也是我们平时非常多书籍所说的Tweened Animation(有人翻译为补间动画)。View Animation分为4大类:AlphaAnimation,RotateAnimation,ScaleAnimation,TranslateAnimation,分别相应透明度。旋转,大小,位移四种变化。

View Animation的效果由四个因素决定:1)初始状态。2)结束状态;3)持续时间;4)Interpolator

所以要定义一个View Animation,你仅仅要定义以上四个因素,中间的过程怎么变化则有系统自己主动计算出来。

当中前3个因素非常easy理解,第四个因素Interpolator比較特别,这个单词不知道怎么翻译比較适合。非常多书籍的翻译都非常奇怪。Interpolator是决定动画进行过程的速度变化。比方:你将一个button从屏幕左側运动到屏幕右側。能够让它一直加速前进。或者先减速然后减速。这就是Interpolator发挥的作用,详细用法以下会说,先从简单的说起。

像Drawable Animation一样,定义一个View Animation能够用代码的方式,也能够用XML文件的方式。我们先来写一个最简单的样例,对一个helloworld字符串进行移动。旋转。放大。变暗。分别用代码实现和XML文件实现。

先用代码实现。

首先新建project:ViewAnimationDemo,并新建一个布局文件:animationjavacode.xml,例如以下:

ViewAnimationDemo\res\layout\animationjavacode.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/translation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="50dp"
        android:text="我要移动" />

    <TextView
        android:id="@+id/rotate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/translation"
        android:layout_marginBottom="50dp"
        android:text="我要旋转" />

    <TextView
        android:id="@+id/scale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/rotate"
        android:layout_marginBottom="50dp"
        android:text="我要变大" />

    <TextView
        android:id="@+id/alpha"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/scale"
        android:layout_marginBottom="200dp"
        android:text="我要变暗" />

    <Button
        android:id="@+id/fire"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/alpha"
        android:text="运动" />

</RelativeLayout>

该XML布局文件相应的Activity例如以下:

ViewAnimationDemo/src/com/CSDN/viewanimationdemo/AnimCodeActivity.java

public class AnimCodeActivity extends Activity {

	private TextView translation;
	private TextView rotate;
	private TextView scale;
	private TextView alpha;

	private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.animationjavacode);

        translation = (TextView) findViewById(R.id.translation);
        rotate = (TextView) findViewById(R.id.rotate);
        scale = (TextView) findViewById(R.id.scale);
        alpha = (TextView) findViewById(R.id.alpha);
        button = (Button) findViewById(R.id.fire);

        button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 1&2: 确定起始状态,结束状态
				TranslateAnimation tAnim = new TranslateAnimation(0, 400, 0, 0);//横向位移400个单位
				RotateAnimation rAnima = new RotateAnimation(0, 70);//顺时针旋转70度
				ScaleAnimation sAnima = new ScaleAnimation(0, 5, 0, 5);//横向放大5倍,纵向放大5倍
				AlphaAnimation aAnima = new AlphaAnimation(1.0f, 0.0f);//从全不透明变为全透明
				// 3: 确定持续时间
				tAnim.setDuration(2000);
				rAnima.setDuration(2000);
				sAnima.setDuration(2000);
				aAnima.setDuration(2000);

				// 4: 确定Interpolator
				tAnim.setInterpolator(new AccelerateDecelerateInterpolator());

				// 启动动画
				translation.startAnimation(tAnim);
				rotate.startAnimation(rAnima);
				scale.startAnimation(sAnima);
				alpha.startAnimation(aAnima);
			}
		});

    }

}

从代码中不难看到,首先确定了动画的起始状态和结束状态,然后通过setDuration(2000)设置持续时间,假设这里不设置持续时间,将默觉得30mx。基本肉眼看不到。最后我们设置了一个Interpolator,此处设置效果是动画先减速进行,然后减速。

默认状态时匀速进行。

没错。Interpolator的基本使用方法就是这么easy。以上代码效果图例如以下:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvQ0haaXJveQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >

接下来解说怎么用xml定义动画,依照android官网的介绍,定义View Animation的xml文件格式例如以下:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@[package:]anim/interpolator_resource"
    android:shareInterpolator=["true" | "false"] >
    <alpha
        android:fromAlpha="float"
        android:toAlpha="float" />
    <scale
        android:fromXScale="float"
        android:toXScale="float"
        android:fromYScale="float"
        android:toYScale="float"
        android:pivotX="float"
        android:pivotY="float" />
    <translate
        android:fromXDelta="float"
        android:toXDelta="float"
        android:fromYDelta="float"
        android:toYDelta="float" />
    <rotate
        android:fromDegrees="float"
        android:toDegrees="float"
        android:pivotX="float"
        android:pivotY="float" />
    <set>
        ...
    </set>
</set>

该文件仅仅能有一个根结点,能够是<set>,<alpha>,<scale>,<translate>,<rotate>,而当中,<set>结点能够包括子节点,即能够包括<set>,<alpha>,<scale>,<translate>,<rotate>,以此类推。

以上须要解说的两个标签属性是android:interpolator和android:shareInterpolator。前者代表你所使用的interpolator。能够是系统自带,也能够是自己定义。

而后者代表,是否将该Interpolator共享给子节点。其他子标签的属性非常easy理解,基本看属性名字就能懂。除了当中两个,android:pivotX和android:pivotY,我们知道,pivot的意思是轴心的意思,所以这两个属性定义的是此次动画变化的轴心位置,默认是左上角,当我们把它们两者都赋值为50%,则变化轴心在中心。

接下来写一个详细的样例,例如以下,还是在刚才的项目中进行。一般我们把定义动画的xml文件放在res/anim文件夹下,首先我们新建一个anim文件夹。然后新建一个xml文件,例如以下:

ViewAnimationDemo/res/anim/myanim.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.4"
        android:fromYScale="1.0"
        android:toYScale="0.6"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="1000" />
    <set
        android:interpolator="@android:anim/accelerate_interpolator"
        android:startOffset="1000">
        <scale
            android:fromXScale="1.4"
            android:toXScale="0.0"
            android:fromYScale="0.6"
            android:toYScale="0.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="400" />
        <rotate
            android:fromDegrees="0"
            android:toDegrees="60"
            android:toYScale="0.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="400" />
    </set>
</set>

上述样例的效果图例如以下:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvQ0haaXJveQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >

上面代码中。有 唯一一个根节点<set>,它有两个子节点<scale>和<set>,然后当中的子节点<set>拥有两个自己的子节点<scale>和<rotate>。

解说一下上面一些没见过的标签属性。

andoird:fillAfter:前面一个样例中,我们的动画结束后helloworld又回到了原来状态,通过设置fillAfter为true,则动画将保持结束的状态。可是。如前一篇博客《Android动画之中的一个:Drawable Animation》所说,View Animation的动画效果是绘制出来的,并不是该组件真正移动了,这个问题我们兴许会继续探讨。

如今仅仅须要知道将fillAfter设置为true之后。动画将保持结束状态,这大多应用于设计连续发生的动画。

startOffset:该属性定义动画推迟多久開始,通过这个属性的设置,我们能够设计一些前后按序发生的动画,当然,除了最后一个发生的动画,其它动画得设置fillAfter为true.

interpolator:这里我们使用了系统自带的interpolator

接下来我们定义一个布局文件,该布局文件仅仅有一张图片。一个button,通过点击button触发图片进行动画,该布局文件比較简单,这里不列出。怎样在该布局文件相应的activity代码中启动动画呢,代码例如以下:

ViewAnimationDemo/src/com/CSDN/viewanimationdemo/AnimaXmlActivity.java

public class AnimaXmlActivity extends Activity {

	private Button btn;
	private ImageView img;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_anima_xml);
		btn = (Button)findViewById(R.id.xml_btn);
		img = (ImageView)findViewById(R.id.xmlAnimImg);

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Animation anim = AnimationUtils.loadAnimation(AnimaXmlActivity.this, R.anim.myanim);
				img.startAnimation(anim);
			}
		});
	}
}

以上代码非常easy理解。我们一般使用AnimationUtils读取定义在xml文件里的动画。

到此为止,关于View Animation的基础知识基本已经覆盖了。接下来写一个详细实践的样例,实现常常见到的側滑功能,如网易新闻这样的:

这个側滑的效果实现并不难。非常多人运用了AsyncTask线程,可是结果你会发现有时会发生明显的卡顿,可是假设使用动画效果将会平滑非常多。我们接下来实现这种功能:

首先新建一个项目:SwipeWithAnim。

并新建一个布局文件activity_main.xml。例如以下

SwipeWithAnim/res/layout/activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <View
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#e23451" />

    <LinearLayout
        android:id="@+id/menu"
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_marginLeft="-380dp"
        android:orientation="horizontal" >

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#eeeee1" />

        <View
            android:id="@+id/dragArea"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:background="#00000000" />
    </LinearLayout>

</FrameLayout>

屏幕显示内容content。左側隐去菜单menu,知识将20dp的透明部分放在屏幕左側,用于触发onTouch事件。该xml文件相应的activity代码例如以下:

SwipeWithAnim/src/com/CSDN/swipewithanim/MainActivity.java

public class MainActivity extends Activity {

	private View menu;
	private final static int SHOW_MENU = 1;
	private final static int HIDE_MENU = -1;
	private int swipe_tag = SHOW_MENU;
	private int max_menu_margin = 0;
	private int min_menu_margin;
	private float beginX;
	private float latestX;
	private float diffX;
	private float latestMargin;

	private FrameLayout.LayoutParams lp;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		menu = findViewById(R.id.menu);
		lp = (FrameLayout.LayoutParams) menu.getLayoutParams();
		min_menu_margin = lp.leftMargin;

		menu.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int action = MotionEventCompat.getActionMasked(event);
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					beginX = event.getX();
					break;
				case MotionEvent.ACTION_MOVE:
					latestX = event.getX();
					diffX = latestX - beginX;
					swipe_tag = diffX > 0 ?

SHOW_MENU : HIDE_MENU;
					latestMargin = lp.leftMargin + diffX;

					if (latestMargin > min_menu_margin
							&& latestMargin < max_menu_margin) {
						lp.leftMargin = (int) (latestMargin);
						menu.setLayoutParams(lp);
					}

					break;
				case MotionEvent.ACTION_UP:
					TranslateAnimation tAnim;
					if (swipe_tag == SHOW_MENU) {
						tAnim = new TranslateAnimation(0, max_menu_margin
								- latestMargin, 0, 0);
						tAnim.setInterpolator(new DecelerateInterpolator());
						tAnim.setDuration(800);
						menu.startAnimation(tAnim);
					} else {
						tAnim = new TranslateAnimation(0, min_menu_margin
								- latestMargin, 0, 0);
						tAnim.setDuration(800);
						menu.startAnimation(tAnim);
					}
					//在动画结束的时刻,移动menu的位置。使menu真正移动。
					tAnim.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							// TODO Auto-generated method stub
							if (swipe_tag == SHOW_MENU) {
								lp.leftMargin = max_menu_margin;
								menu.setLayoutParams(lp);
							} else {
								lp.leftMargin = min_menu_margin;
								menu.setLayoutParams(lp);
							}
							menu.clearAnimation();
						}
					});

					break;
				}
				return true;
			}
		});

	}

}

如上代码。监听menu的onTouch事件,然后依据移动距离移动menu。当手指拿起来时,启动动画,使移动继续进行到结束。

我们上面提到,View Animation仅仅是绘制出来的效果,发生动画的组件并不是真正移动了,那么此处为了解决问题,我们监听了AnimationListener。在动画结束时,将menu的位置移动到动画结束的位置,这样就成功移动了menu。效果图例如以下。因为截图软件关系,看起来会卡顿,在真机上測试则全然平滑。

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvQ0haaXJveQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >

最后附上这篇博客前后的两份源代码:

ViewAnimationDemo

SwipeWithAnim

版权声明:本文博主原创文章,博客,未经同意不得转载。

时间: 2024-08-10 00:04:20

Android动画之二:View Animation的相关文章

Android动画三部曲之一 View Animation &amp; LayoutAnimation

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/50612827 本篇文章对android的Tween动画和帧动画以及布局动画进行总结. Tween动画 XML语法介绍 插值器 Interpolator 自定义Interpolator 公共XML属性及对应的方法 ScaleAnimation 缩放动画 xml定义缩放动画 代码定义缩放动画 RotateAnimation 旋转动画 xml中设置旋转动画 代码中设置旋转动画 Transl

Android动画效果之Frame Animation(逐帧动画)(二)(

前言: 上一篇介绍了Android的Tween Animation(补间动画) Android动画效果之Tween Animation(补间动画),今天来总结下Android的另外一种动画Frame Animation(逐帧动画). Frame Animation(逐帧动画): 逐帧动画(Frame-by-frame Animations)从字面上理解就是一帧挨着一帧的播放图片,就像放电影一样.和补间动画一样可以通过xml实现也可以通过java代码实现.接下来借助目前项目中的一个开奖的动画来总结

Android动画效果之Frame Animation(逐帧动画)

前言: 上一篇介绍了Android的Tween Animation(补间动画) Android动画效果之Tween Animation(补间动画),今天来总结下Android的另外一种动画Frame Animation(逐帧动画). 其他几种动画效果: Android动画效果之Tween Animation(补间动画) Android动画效果之Frame Animation(逐帧动画) Android动画效果之初识Property Animation(属性动画) Android动画效果之Prop

安卓开发_浅谈Android动画(二)

在学习了四个基本动画之后,现在要学习一些更有用的效果 先给出所有的动画xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <set xmlns:android="http://schemas.android.com/apk/res/android" > 3 4 <alpha 5 android:duration="3000" 6 android:fromA

【Android界面实现】View Animation 使用介绍

转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992 我们可以使用view animation 动画系统来给View控件添加tween动画(下称"补间动画"),补间动画通过计算一些动画参数,比如说开始点,结束点,大小,旋转角度和一些其他的动画参数,来实现动画效果. 补间动画可以给View对象添加一系列简单的变换,比如位置,大小,角度或者是透明度.所以,如果你有一个TextView对象,你可以移动,旋转或者是变大.如果它有一个背景图片,背景图片也会随

Android动画效果之Tween Animation(补间动画)(一)

前言: 最近公司项目下个版本迭代里面设计了很多动画效果,在以往的项目中开发中也会经常用到动画,所以在公司下个版本迭代开始之前,抽空总结一下Android动画.今天主要总结Tween Animation(补间动画). Tween Animation(补间动画): Tween动画,通过对View的内容进行一系列的图形变换 (包括平移.缩放.旋转.改变透明度)来实现动画效果.动画效果的定义可以采用XML来做也可以采用编码来做. 动画类型 XML配置方式 Java代码实现方式 渐变透明度动画效果 <al

动画的使用&mdash;View Animation

View Animation定义了下面的四种动画效果: 缩放(scale).位移(translation).旋转(rotation).透明(alpha)   缩放动画: ScaleAnimation(float fromX, float toX, float fromY, float toY, float pivotX, float pivotY) 看ScaleAnimation的构造函数,各个参数的含义都很清楚 fromX: 理解为对象缩放前的宽度 toX:对象x需要缩放到多大 其他的两个带Y

Android 动画具体解释View动画

为了让用户更舒适的在某些情况下,利用动画是那么非常有必要的.Android在3.0一旦支持两种动画Tween动漫Frame动画.Tween动画支持简单的平移,缩放,旋转,渐变.Frame动画就像Gif图通过一系列图片来模拟动画效果,而在Android 3.0以后引入了新的动画就是属性动画(property animation).Android 分享一个简单有趣的动画效果 就是利用了属性动画. 今天我们主要来学习Tween动画也就是View动画. View 动画仅仅能应用于View对象,并且仅仅支

Android动画之三:Property Animation(上)

来完成这个Android动画系列,之前写了View Animation和Drawable Animation,接下来讲解三种动画中的最后一种,Property Animation,这也是Android动画中最强大的一部分,同时也是相对最复杂的一部分. Property Animation与Value Animation的区别 Property Animation翻译为属性动画,从Android3.0开始引入,相比与View Animation,官方更推荐开发者使用Property Animati