View动画的特殊使用场景
View
动画还可以在一些特殊的场景下使用,比如在ViewGroup
中可以控制子元素的出场效果。
1. LayoutAnimation
LayoutAnimation
作用于ViewGroup
,为ViewGroup
指定一个动画,这样当它的子元素出场时都会具有这种动画效果。
为了给ViewGroup
的子元素加上出场效果,遵循如下几个步骤:
1.为子元素指定具体的入场动画
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:shareInterpolator="true">
<translate
android:fromXDelta="500"
android:toXDelta="0"/>
<alpha
android:fromAlpha="0"
android:toAlpha="1"/>
</set>
2.定义LayoutAnimation
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation
xmlns:android="http://schemas.android.com/apk/res/android"
android:delay="0.5"
android:animationOrder="normal"
android:animation="@anim/anim_item">
</layoutAnimation>
android:delay
表示子元素开始动画的时间延迟。比如子元素入场动画的时间周期是300ms
,那么0.5
表示每个子元素都需要延迟150ms
才能播放入场动画。总体来说,第一个子元素延迟150ms
开始播放入场动画,第二个子元素延迟300ms
开始播放入场动画。android:animationOrder
表示子元素动画的顺序,有三种选项:normal
,reverse
,random
,其中normal
表示顺序显示,即排在前面的子元素先开始播放入场动画,reverse
表示逆向显示,即排在后面的子元素先开始播放入场动画,random
则是随机播放入场动画。-
android:animation
为子元素指定具体的入场动画。
开心wonderful的图
3. 为ViewGroup指定android:layoutAnimation
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff4f7f9"
android:cacheColorHint="#00000000"
android:divider="#dddbdb"
android:dividerHeight="1.0px"
android:layoutAnimation="@anim/anim_layout"
android:listSelector="@android:color/transparent">
</ListView>
除了在xml
中指定android:layoutAnimation
外,还可以通过LayoutAnimationController
来实现。
Animation animation = AnimationUtils.loadAnimation(this,R.anim.anim_item);
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.5f);
controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
listView.setAnimation(animation);
2. Activity的切换效果
Activity
有默认的切换效果,但是这个效果是我们可以自定义的,主要用到overridePendingTransition(int enterAnim,int exitAnim)
这个方法,这个方法必须在startActivity(Intent)
或者finish()
之后被调用才能生效。
-
enterAnim
Activity
被打开时,所需的动画资源id
-
exitAnim
Activity
被暂停时,所需的动画资源id
当启动一个Activity
时
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.enter_anim,R.anim.exit_anim);
当Activity
退出时,为其指定切换效果
finish();
overridePendingTransition(R.anim.enter_anim,R.anim.exit_anim);
需要注意的是,overridePendingTransition
这个方法必须位于startActivity
或者finish
后面,否则动画效果将不起作用。
Fragment
也可以添加切换动画,由于Fragment
是在API11
中新引入的类,因此为了兼容性我们需要使用support-v4
这个兼容包,在这种情况下我们可以通过FragmentTransaction
中的setCustomAnimations()
方法来添加切换动画,这个切换动画需要是View
动画。