Android studio 学习4:实现2D翻转
程序员文章站
2022-04-28 19:13:52
...
Android studio :实现2D翻转
一、准备
1、需要两张图片
2、了解FrameLayout布局
二、具体代码实现
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"
tools:context=".MainActivity">
<ImageView
android:id="@+id/a"
android:src="@drawable/a"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/b"
android:src="@drawable/b"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
java代码:
import androidx.appcompat.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;
//创建动画1
private ScaleAnimation sato0 = new ScaleAnimation( 1,0,1,1,
Animation.RELATIVE_TO_PARENT,0.5f,Animation.RELATIVE_TO_PARENT,0.5f );
//创建动画2
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) {
// imageA.startAnimation( sato0 );
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 = findViewById( R.id.a );
imageB = findViewById( R.id.b );
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.setAnimation( sato1 );
}else {
imageB.setAnimation( null );
showImageA();
imageA.startAnimation( sato1 );
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
} );
}
}