Android 2D翻转动画效果的实现

时间:2023-02-10 20:07:56

首先分为2步:

第一步实现创建动画;

第二部添加动画 监听。

Activity部分代码:

package com.example.wbw.card2d;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
private ImageView imageA;
private ImageView imageB;
private ScaleAnimation sato0=new ScaleAnimation(1,0,1,1,
Animation.RELATIVE_TO_PARENT,0.5f,Animation.RELATIVE_TO_PARENT,0.5f);
private ScaleAnimation sato1=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);
initView();
findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(imageA.getVisibility()==View.VISIBLE){
imageA.startAnimation(sato0);
}else {
imageB.startAnimation(sato0);
}
}
});
}
private void showImageA(){
imageA.setVisibility(View.VISIBLE);
imageB.setVisibility(View.INVISIBLE);
}
private void showImageB(){
imageA.setVisibility(View.INVISIBLE);
imageB.setVisibility(View.VISIBLE);
}
private void initView(){
imageA= (ImageView) findViewById(R.id.ivA);
imageB= (ImageView) findViewById(R.id.ivB);
showImageA();
sato0.setDuration(500);
sato1.setDuration(500);
sato0.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {
if(imageA.getVisibility()==View.VISIBLE){
imageA.setAnimation(null);
showImageB();
imageB.startAnimation(sato1);
}else {
imageB.setAnimation(null);
showImageA();
imageA.startAnimation(sato1);
}

}

@Override
public void onAnimationRepeat(Animation animation) {

}
});
}
}

界面部分代码:

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.wbw.card2d.MainActivity">

<ImageView
android:id="@+id/ivA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image_a"
/>
<ImageView
android:id="@+id/ivB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image_b"
/>
</FrameLayout>

总结:2D翻转在很多app的部分都可以使用,特别是相册查看时使用,可使用户体验效果更好。这只实现了2D翻转的基本功能,从一张图片翻转到另外一张图片。还可以有更多改进。