进阶篇-用户界面:9.android动画-布局动画

1.为布局添加动画效果

(1)在布局文件中添加一排纵向的按钮。

(2)在MainActivity中给布局添加动画效果。这个布局的动画效果影响的是该布局下所有子对象的。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity{
    private LinearLayout la ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        la = (LinearLayout) findViewById(R.id.liner);
        ScaleAnimation sa = new ScaleAnimation(0,1,0,1);
        sa.setDuration(1000);
        LayoutAnimationController lac = new LayoutAnimationController(sa,0.5f);//0.5f is the delay of layoutAnimation,the second button begins to show up when the first
                                                                               //button is to half the time.
        lac.setOrder(LayoutAnimationController.ORDER_NORMAL);                  //Class LayoutAnimationController gives three kinds of order:nomal,random and reverse.
        la.setLayoutAnimation(lac);
    }
}

效果是按钮一个一个出现,并且带有缩放效果

2.布局内容改变动画

在布局文件中添加:

android:animateLayoutChanges="true"

这样的话,在源码中更改布局,添加和删除子对象,就会有动画效果,默认的动画效果是透明度变化,如果想要自定义动画效果,参考为布局添加动画效果。

3.使用资源文件布局动画

(1)在res文件夹下创建一个scale.xml:

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXScale="0"
    android:toXScale="1"
    android:fromYScale="0"
    android:toYScale="1"
    android:duration="1000"/>

(2)再创建一个animcontroller.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation  xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/scale"
    android:delay="0.5">

</layoutAnimation>

(3)再布局文件中添加属性:

android:layoutAnimation="@anim/animcontroller"