android基础:动画案例(图片翻转)

layout->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"
    android:id="@+id/root">
    
    <ImageView 
        android:id="@+id/imageA"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/image_a"
        />

    <ImageView 
        android:id="@+id/imageB"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/image_b"
        />
</FrameLayout>

MainActivity.java

package com.jikexueyuan.card2d;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private ImageView imageA;
	private ImageView imageB;

	// 定义动画
	ScaleAnimation ani1 = new ScaleAnimation(1, 0, 1, 1, Animation.RELATIVE_TO_PARENT, 0.5f,
			Animation.RELATIVE_TO_PARENT, 0.5f);
	ScaleAnimation ani2 = new ScaleAnimation(0, 1, 1, 1, Animation.RELATIVE_TO_PARENT, 0.5f,
			Animation.RELATIVE_TO_PARENT, 0.5f);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		imageA = (ImageView) findViewById(R.id.imageA);
		imageB = (ImageView) findViewById(R.id.imageB);

		// 默认显示A
		imageA.setVisibility(View.VISIBLE);
		imageB.setVisibility(View.INVISIBLE);

		// 设置动画时间
		ani1.setDuration(700);
		ani2.setDuration(700);

		// 点击界面,显示动画1
		this.findViewById(R.id.root).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (imageA.getVisibility() == View.VISIBLE) {
					imageA.startAnimation(ani1);
				} else {
					imageB.startAnimation(ani1);
				}

			}
		});

		// 添加,动画1结束后,启动动画2
		ani1.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				if (imageA.getVisibility() == View.VISIBLE) {

					imageB.setVisibility(View.VISIBLE);
					imageA.setVisibility(View.INVISIBLE);

					imageA.setAnimation(null);
					imageB.startAnimation(ani2);

				} else {

					imageA.setVisibility(View.VISIBLE);
					imageB.setVisibility(View.INVISIBLE);

					imageB.setAnimation(null);
					imageA.startAnimation(ani2);
				}

			}
		});

	}

}

  

你可能感兴趣的:(android)