动画淡入淡出不起作用

时间:2018-05-29 09:30:32

标签: java android

使用此代码进行淡入淡出,这不起作用。 任何想法?

公共类MainActivity扩展了AppCompatActivity {

public void picChange(View view) {

    ImageView youngF = (ImageView) findViewById(R.id.firstPic);

    ImageView biggerF = (ImageView) findViewById(R.id.secondPic);


    youngF.animate().alpha(0f).setDuration(2000);
    biggerF.animate().alpha(1f).setDuration(2000);
}


public void back (View view) {

    ImageView youngBack = (ImageView) findViewById(R.id.firstPic);

    ImageView biggBack = (ImageView) findViewById(R.id.secondPic);

    biggBack.animate().alpha(0f).setDuration(2000);
    youngBack.animate().alpha(1f).setDuration(2000);

}

使用此代码进行淡入淡出,这不起作用。 任何想法?

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

}

2 个答案:

答案 0 :(得分:1)

创建XML文件以定义动画

For Fade In animation fade_in.xml

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

对于淡出动画fade_out.xml

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

然后在MainActivity

public void picChange(View view) {

ImageView youngF = (ImageView) findViewById(R.id.firstPic);

ImageView biggerF = (ImageView) findViewById(R.id.secondPic);

Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
                img.startAnimation(animFadeIn);

Animation animFadeOut = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
                    img.startAnimation(animFadeOut);

youngF.startAnimation(animFadeIn);
biggerF.startAnimation(animFadeOut);

}

答案 1 :(得分:0)

Animation fadeIn = new AlphaAnimation(0, 1);
    fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
    fadeIn.setDuration(1000);

    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
    fadeOut.setStartOffset(1000);
    fadeOut.setDuration(1000);

    AnimationSet animation = new AnimationSet(false); //change to false
    animation.addAnimation(fadeIn);
    imgone.setAnimation(animation);

    AnimationSet animation1 = new AnimationSet(false); //change to false
    animation1.addAnimation(fadeOut);
    imgtwo.setAnimation(animation1);