Android

Android动画(二)之View动画的特殊使用场景

2019-04-01  本文已影响20人  12313凯皇

一、前言

首先呢,View动画有四种类型,分别是平移动画,缩放动画、旋转动画和透明度动画。除了这四种形式外,View动画还可以在一些特殊的场景下使用,比如ViewGroup中可以控制子元素的出场效果,在Activity中可以实现不同Activity之间的切换效果等。

对于View的四种类型不太了解的可以查看我的另一篇文章:Android动画(一)之View动画,下面将简单的介绍下上面所提到的两种特殊使用场景:

二、LayoutAnimation

LayoutAnimation作用于ViewGroup,为ViewGroup指定一个动画,这样当它的子元素出场时都会具有这种动画效果。这种效果常常被用在ListView上,我们时常会看到一种特殊的ListView,它的每个item都以一定的动画的形式出现,其实这并非什么高深的技术,它使用的就是LayoutAnimationLayoutAnimation也是一个View动画,为了给ViewGroup的子元素加上出场效果,遵循如下几个步骤。

1. 定义LayoutAnimation
// res/drawable/anim_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/anim_item"
    android:animationOrder="normal"
    android:delay="0.5" />

它的属性的含义如下所示:

2. 为子元素指定具体的入场动画:
// res/anim/anim_item/xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:shareInterpolator="true">

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

    <translate
        android:fromXDelta="500"
        android:toXDelta="0" />
</set>
3. 为ViewGroup指定属性:

为ViewGroup指定属性:对于ListView来说,这样ListViewitem就具有出场动画了,这种方式适用于所有的ViewGroup,如下所示:

 <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" />

除了在XML中指定LayoutAnimation外,还可以通过LayoutAnimationController来实现,具体代码如下所示:

ListView listView = findViewById(R.id.list);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_item);
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.5f);
controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
listView.setLayoutAnimation(controller);

上述动画执行效果:


三、Activity的切换效果

Activity有默认的切换效果,但是这个效果我们是可以自定义的,主要用到overridePendingTransition(int enterAnim, int exitAnim)这个方法,这个方法必须在stratActivity(Intent)或者finish()之后被调用才能生效,它的参数含义如下:

当启动一个Activity时,可以按照如下方式为其添加自定义的切换效果:

Intent intent = new Intent(this, TestActivity.calss);
startActivity(intent);
overridePendingTransition(R.anim.enter_anim,R.anim.exit_anim);

Activity退出时,也可以为其制定自己的切换效果:

@Override
public void finish() {
    super.finish();
    overridePendingTransition(R.anim.enter_anim,R.anim.exit_anim);
}

Fragment也可以添加切换动画,由于Fragment是在API 11中新引入的类,因此为了兼容性我们需要使用 support-v4这个兼容包,在这种情况下我们可以通过FragmentTransaction中的setCustomAnimations()方法来添加切换动画。这个切换动画需要是View动画,之所以不能采用属性动画是因为属性动画也是API 11新引入的。还有其他方式可以给ActivityFragment添加切换动画,但是它们大多都有兼容性问题,在低版本上无法使用,因此不具备很高的使用价值,这里就不再一一介绍了。

相关推荐:Android动画(一)之View动画Android动画(三)之属性动画

上一篇 下一篇

猜你喜欢

热点阅读