android中有很多动画效果,用起来非常会对APP展示有不错的效果,这里就来简单实现一个图片2D翻转的动画效果,以此来熟悉Android中动画效果的使用。后面会给出源码(注意:本事例使用Android studio 开发的),
1、首先看看主布局:
<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=".MainActivity">
<ImageView
android:id="@+id/iamge1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/img1"/>
<ImageView
android:id="@+id/iamge2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/img2"/>
</FrameLayout>
主布局很简单,就是使用FrameLayout作为父容器,在其中加入两个imageview;用这两个imageview作为动画演示。
2、主代码:
package com.example.my.scaleanimation;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 image1,image2,image3,image4,image5;
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 v) {
if (image1.getVisibility() == View.VISIBLE){
image1.startAnimation(sato0);
}else{
image2.startAnimation(sato0);
}
}
});
}
private void showImage1(){
image1.setVisibility(View.VISIBLE);
image2.setVisibility(View.GONE);
}
private void showImage2(){
image1.setVisibility(View.GONE);
image2.setVisibility(View.VISIBLE);
}
private void initView(){
image1 = (ImageView) findViewById(R.id.iamge1);
image2 = (ImageView) findViewById(R.id.iamge2);
showImage1();
sato0.setDuration(500);
sato1.setDuration(500);
sato0.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (image1.getVisibility() == View.VISIBLE){
image1.setAnimation(null);
showImage2();
image2.startAnimation(sato1);
}else{
image2.setAnimation(null);
showImage1();
image1.startAnimation(sato1);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
关于ScaleAnimation 官方给出了非常详细的解释:
请点击详解地址查看,作为开发者,要学会查看官方文档,具备一定的英文能力是很关键的。
下面请看看效果,是不是很酷,实现起来也非常简单: