如何在android中使用animate()。alpha()。setDuration()使图像褪色?

时间:2018-01-04 17:01:40

标签: java android xml android-studio animation

我让图像淡出一次并显示第二张图像。如何对显示的第二个图像执行相同的操作,然后点击它褪色并再次显示第一个图像?我尝试了褪色和反叛,但是一个不起作用。

这是XML

            <ImageView
             android:id="@+id/imageView2"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_alignParentLeft="true"
             android:layout_alignParentStart="true"
             android:layout_alignParentTop="true"
             app:srcCompat="@drawable/a"
             android:onClick="fade"
             android:alpha="1" />

            <ImageView
             android:id="@+id/imageView1"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_alignParentLeft="true"
             android:layout_alignParentStart="true"
             android:layout_alignParentTop="true"
             app:srcCompat="@drawable/b"
             android:onClick="refade"
             android:alpha="1" />

以下是Java代码:

public void fade(View view){

    ImageView s1 = (ImageView) findViewById(R.id.imageView2);
    s1.animate().alpha(0f).setDuration(2000);

    Log.i("Infor", "The first image started fading");

    ImageView s2 = (ImageView) findViewById(R.id.imageView1);
    s2.animate().alpha(1f).setDuration(2000);

    Log.i("Infor", "The second appeared");
}


public void refade(View view){

    ImageView s2 = (ImageView) findViewById(R.id.imageView1);
    s2.animate().alpha(0f).setDuration(1000);

    Log.i("Oiii", "The second image started fading");

    ImageView s1 = (ImageView) findViewById(R.id.imageView2);
    s1.animate().alpha(1f).setDuration(2000);

    Log.i("Oiii", "The first appeared");
}

1 个答案:

答案 0 :(得分:0)

我这样做了:

        Animation fade = AnimationUtils.loadAnimation(fa, R.anim.fade);
        Animation fade2 = AnimationUtils.loadAnimation(fa, R.anim.fade2);

        fade.reset();
        fade2.reset();

        imageView.clearAnimation();
        imageView.startAnimation(fade);

        fade.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                   fade2.reset();
                   imageView2.clearAnimation();
                   imageView2.startAnimation(fade2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

和fade.xml:

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="0.0" android:toAlpha="1.0"
    android:duration="1000" />