I want to have a 2 second animation of an ImageView that spends 1000ms fading in and then 1000ms fading out.
Here's what I have so far in my ImageView constructor:
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);
AnimationSet animation = new AnimationSet(true);
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
When I run that animation, nothing shows up. However, when I remove one of the alpha animations, the behavior works as expected.
Things I have already tried:
Every conceivable combination of setFillBefore, setFillAfter, and setFillEnabled.
Adding a LinearInterpolator to the AnimationSet.
Figured out my own problem. The solution ended up being based in interpolators.
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);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
If you are using Kotlin
val fadeIn = AlphaAnimation(0f, 1f)
fadeIn.interpolator = DecelerateInterpolator() //add this
fadeIn.duration = 1000
val fadeOut = AlphaAnimation(1f, 0f)
fadeOut.interpolator = AccelerateInterpolator() //and this
fadeOut.startOffset = 1000
fadeOut.duration = 1000
val animation = AnimationSet(false) //change to false
animation.addAnimation(fadeIn)
animation.addAnimation(fadeOut)
this.setAnimation(animation)
I know that this already has been answered but.....
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000"
android:repeatCount="infinite"
android:repeatMode="reverse"
/>
Quick and easy way to quickly do a fade in and out with a self repeat. Enjoy
EDIT :
In your activity add this:
yourView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.yourAnimation));
viewToAnimate.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
#Override
public void run() {
viewToAnimate.animate().alpha(0).setDuration(1000).setInterpolator(new AccelerateInterpolator()).start();
}
}).start();
Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.
// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha", 1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);
final AnimatorSet mAnimationSet = new AnimatorSet();
mAnimationSet.play(fadeIn).after(fadeOut);
mAnimationSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimationSet.start();
}
});
mAnimationSet.start();
Another alternative:
No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.
So you can do this with Animation.REVERSE like this:
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);
then onAnimationEnd:
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
//TODO: Run when animation start
}
#Override
public void onAnimationEnd(Animation animation) {
//TODO: Run when animation end
}
#Override
public void onAnimationRepeat(Animation animation) {
//TODO: Run when animation repeat
}
});
As I believe in the power of XML (for layouts), this is the equivalent for the accepted answer, but purely as an animation resource:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:interpolator/accelerate_decelerate"
android:fillAfter="true">
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="1000" />
<alpha
android:fromAlpha="1"
android:toAlpha="0"
android:duration="1000"
android:startOffset="1000"/>
</set>
The fillAfter is for the fade to remain after completing the animation. The interpolator handles interpolation of the animations, as you can guess. You can also use other types of interpolators, like Linear or Overshoot.
Be sure to start your animation on your view:
yourView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fade));
Here is what I used to fade in/out Views, hope this helps someone.
private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
AnimatorSet mAnimationSet = new AnimatorSet();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA, 1f, 0f);
fadeOut.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
fadeOutTarget.setVisibility(View.GONE);
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
fadeOut.setInterpolator(new LinearInterpolator());
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
fadeIn.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
fadeInTarget.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationEnd(Animator animation) {}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
fadeIn.setInterpolator(new LinearInterpolator());
mAnimationSet.setDuration(duration);
mAnimationSet.playTogether(fadeOut, fadeIn);
mAnimationSet.start();
}
AnimationSets don't appear to work as expected at all. In the end I gave up and used the Handler class's postDelayed() to sequence animations.
If you use Animator for make animation you can
anim (directory) -> fade_out.xml
<?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
android:propertyName="alpha"
android:valueFrom="0"
android:valueTo="1"
xmlns:android="http://schemas.android.com/apk/res/android"/>
In java
Animator animator = AnimatorInflater.loadAnimator(context, R.animator.fade_out);
animator.setTarget(the_view_you_want_to_animation);
animator.setDuration(1000);
animator.start();
Other way to make animation fade out with only java code is
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(the_view_you_want_to_animation, "alpha", 1f, 0);
fadeOut.setDuration(2000);
fadeOut.start();
You can also use animationListener, something like this:
fadeIn.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
this.startAnimation(fadeout);
}
});
I really like Vitaly Zinchenkos solution since it was short.
Here is an even briefer version in kotlin for a simple fade out
viewToAnimate?.alpha = 1f
viewToAnimate?.animate()
?.alpha(0f)
?.setDuration(1000)
?.setInterpolator(DecelerateInterpolator())
?.start()
Related
I am trying to slid a view from the bottom of the screen and collapse another view a little everything will fit correctly.
I have managed to do that with the attribute animateLayoutChanges and 2 simple xml animations slid_up.xml and slid_down.xml.
My problem is that the animation that happens to ViewPager from the attribute animateLayoutChanges isn't smooth.
Is there a way to fix that?
slid_up.xml
<translate
android:duration="1000"
android:fromYDelta="100%"
android:toYDelta="0" />
</set>
slid_down.xml
<translate
android:duration="1000"
android:fromYDelta="0"
android:toYDelta="100%" />
</set>
P.S. I have tried to create custom animators as Height animators but it messes with the original height of the view.
HeightResizeAnimation
public class HeightResizeAnimation extends Animation {
private View mView;
private float mToHeight;
private float mFromHeight;
private int duration = 300;
public HeightResizeAnimation(View v, float offset) {
mView = v;
mToHeight = v.getHeight() + offset;
mFromHeight = v.getHeight();
setDuration(duration);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float newHeight = (mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
mView.getLayoutParams().height = (int) newHeight;
mView.requestLayout();
}
}
after the animation the height will no longer be as match_parent that was before the animation.
Update
Here is the animation that happens now
You can see that the fab animation to bottom isn't smooth also for the viewpager that the fab is child
It seems like you just want to show a snackbar + move the FAB along with it as it shows?
To do so you could use a combination of Snackbar and CoordinatorLayout from the Android Support Library: http://www.androidhive.info/2015/09/android-material-design-snackbar-example/
In your xml layout add the following in the View:
android:visibility="gone"
android:alpha="0"
android:id="#+id/text_view_liked"
I am asumming the view to be TextView.
On the click of ImageView liked animate the text_view_liked with the following:
final TextView textViewLiked = (TextView) findViewById(R.id.text_view_get_liked);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
PropertyValuesHolder pvhYTextViewLiked = PropertyValuesHolder
.ofFloat(View.Y,
textViewLiked.getBottom(),
(textViewLiked.getBottom() - textViewLiked.getHeight()));
PropertyValuesHolder pvhAlphaTextViewLiked = PropertyValuesHolder
.ofFloat(View.ALPHA, 0f, 1f);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(textViewLiked,
pvhYTextViewLiked,
pvhAlphaTextViewLiked);
ObjectAnimator objectAnimatorFab = ObjectAnimator.ofFloat(fab, View.Y, fab.getY(),
fab.getY() - textViewLiked.getHeight());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(objectAnimator).with(objectAnimatorFab);
animatorSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
textViewLiked.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
PropertyValuesHolder pvhYTextViewLiked = PropertyValuesHolder
.ofFloat(View.Y,
textViewLiked.getTop(),
(textViewLiked.getTop() + textViewLiked.getHeight()));
PropertyValuesHolder pvhAlphaTextViewLiked = PropertyValuesHolder
.ofFloat(View.ALPHA, 1f, 0f);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(textViewLiked,
pvhYTextViewLiked,
pvhAlphaTextViewLiked);
ObjectAnimator objectAnimatorFab = ObjectAnimator.ofFloat(fab, View.Y, fab.getY(),
fab.getY() + textViewLiked.getHeight());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(objectAnimator).with(objectAnimatorFab);
animatorSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textViewLiked.setVisibility(View.GONE);
}
});
animatorSet.start();
}
}, 1000);
}
});
You can adjust the duration accordingly
new Handler is created just to automate the process of progress indicator is finished. You can just call on the finish of progress indicator.
After all the solution was to use the android:clipChildren="false"
As can be seen on the gif, the FAB is getting cropped while it is going down to the original position. So after I have used the android:clipChildren="false" on the parent of the FAB viewPager then the FAB isn't getting cropped anymore.
I have an application where i spawn a new enemy every 4 seconds. the enemy goes from right to left using anTranslateAnimation. This animation takes 7 seconds total.
The problem that I'm facing now is that when the animation is running, every time that i spawn a new enemy, the animation stops for the old one and starts animating the new enemy.
Is there any way to animate two different objects using the same TranslateAnimation?
Just in case, here is my animation
translate= new TranslateAnimation(
Animation.ABSOLUTE, (float) 1.0,
Animation.ABSOLUTE, (float) -4.0,
Animation.ABSOLUTE,0,
Animation.ABSOLUTE,0);
translate.setDuration(10000);
translate.setFillAfter(true);
//newIV is the enemy's ImageView
newIV.startAnimation(translate);
You can apply animation like this
make an animation xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="500"
/>
</set>
Then code in class
final Animation RightToLeft = AnimationUtils.loadAnimation(context,
R.anim.right_to_left);
((ImageView)findViewById(R.id.yourImage))
.startAnimation(RightToLeft);
Hope it will help.
You can set a same animation to Different views in same position.try to use animationLisener
translate.setAnimationListener(new TranslateAnimation.AnimationListener() { #Override
public void onAnimationStart(Animation animation) { }
#Override
public void onAnimationRepeat(Animation animation) { }
#Override
public void onAnimationEnd(Animation animation)
{
animation.setFillAfter(false);
RelativeLayout.LayoutParams params =(RelativeLayout.LayoutParams)mLogo.getLayoutParams();
//Set your firest view layout or hide the previous newIV
//This ll avoid filckering
animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
animation.setDuration(1);
ImageView mLogo = new ImageView(activity);// Second enemy as u said
animation = new TranslateAnimation(
Animation.ABSOLUTE, (float) 1.0,
Animation.ABSOLUTE, (float) -4.0,
Animation.ABSOLUTE,0,
Animation.ABSOLUTE,0);
mLogo.startAnimation(animation);mLogo.setLayoutParams(params);
mLogo.clearAnimation();
mLogo.startAnimation(animation);
}
});
This ll animate When first enemy going to end create a new instance of animation and use.
Using this code I only have a fade in, I'm looking for how to add a fade out as well. I've added another xml called "fadeout" but I can't integrate it in my code.
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
imageView.startAnimation(fadeInAnimation);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
imageView.startAnimation(fadeInAnimation);
}
}
fadein.xml
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="Your Duration(in milisecond)"
android:repeatCount="infinite"/>
</set>
Here is my solution. It uses AnimatorSet. AnimationSet library was too buggy to get working. This provides seamless and infinite transitions between fade in and out.
public static void setAlphaAnimation(View v) {
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(v, "alpha", 1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(v, "alpha", .3f, 1f);
fadeIn.setDuration(2000);
final AnimatorSet mAnimationSet = new AnimatorSet();
mAnimationSet.play(fadeIn).after(fadeOut);
mAnimationSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimationSet.start();
}
});
mAnimationSet.start();
}
This is Good Example for Fade In and Fade Out Animation with Alpha Effect
Animate Fade In Fade Out
UPDATED :
check this answer may this help you
I´ve been working in Kotlin (recommend to everyone), so the syntax might be a bit off.
What I do is to simply to call:
v.animate().alpha(0f).duration = 200
I think that, in Java, it would be the following.:
v.animate().alpha(0f).setDuration(200);
Try:
private void hide(View v, int duration) {
v.animate().alpha(0f).setDuration(duration);
}
private void show(View v, int duration) {
v.animate().alpha(1f).setDuration(duration);
}
According to the documentation AnimationSet
Represents a group of Animations that should be played together. The
transformation of each individual animation are composed together into
a single transform. If AnimationSet sets any properties that its
children also set (for example, duration or fillBefore), the values of
AnimationSet override the child values
AnimationSet mAnimationSet = new AnimationSet(false); //false means don't share interpolators
Pass true if all of the animations in this set should use the
interpolator associated with this AnimationSet. Pass false if each
animation should use its own interpolator.
ImageView imageView= (ImageView)findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mAnimationSet.addAnimation(fadeInAnimation);
mAnimationSet.addAnimation(fadeOutAnimation);
imageView.startAnimation(mAnimationSet);
I hope this will help you.
we can simply use:
public void animStart(View view) {
if(count==0){
Log.d("count", String.valueOf(count));
i1.animate().alpha(0f).setDuration(2000);
i2.animate().alpha(1f).setDuration(2000);
count =1;
}
else if(count==1){
Log.d("count", String.valueOf(count));
count =0;
i2.animate().alpha(0f).setDuration(2000);
i1.animate().alpha(1f).setDuration(2000);
}
}
where i1 and i2 are defined in the onCreateView() as:
i1 = (ImageView)findViewById(R.id.firstImage);
i2 = (ImageView)findViewById(R.id.secondImage);
count is a class variable initilaized to 0.
The XML file is :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/secondImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="animStart"
android:src="#drawable/second" />
<ImageView
android:id="#+id/firstImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="animStart"
android:src="#drawable/first" />
</RelativeLayout>
#drawable/first and #drawable/second are the images in the drawable folder in res.
You can do this also in kotlin like this:
contentView.apply {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
alpha = 0f
visibility = View.VISIBLE
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
animate()
.alpha(1f)
.setDuration(resources.getInteger(android.R.integer.config_mediumAnimTime).toLong())
.setListener(null)
}
read more about this in android docs
Please try the below code for repeated fade-out/fade-in animation
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.3f);
anim.setRepeatCount(Animation.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
anim.setDuration(300);
view.setAnimation(anim); // to start animation
view.setAnimation(null); // to stop animation
FOR FADE add this first line with your animation's object.
.animate().alpha(1).setDuration(2000);
FOR EXAMPLE
Today, I got stuck with this problem. This worked for me:
#JvmStatic
fun setFadeInFadeOutAnimation(v: View?) {
val fadeIn = ObjectAnimator.ofFloat(v, "alpha", 0.0f, 1f)
fadeIn.duration = 300
val fadeOut = ObjectAnimator.ofFloat(v, "alpha", 1f, 0.0f)
fadeOut.duration = 2000
fadeIn.addListener(object : AnimatorListenerAdapter(){
override fun onAnimationEnd(animation: Animator?) {
fadeOut.start()
}
})
fadeIn.start()
}
I'm trying to set up 2 layouts - I want one layout to slide up, and when it's finished another layout should fade in.
I've managed to get it working, but at the end of the two animation and first layout blinks once.
How can I solve it?
Here's the code(first layout is named titleLay and the second one is called registerLayout)-
final TranslateAnimation slide = new TranslateAnimation(0, 0, 0,-100 );
slide.setDuration(500);
slide.setFillAfter(true);
slide.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
RelativeLayout registerLayout = (RelativeLayout) findViewById(R.id.registerLay);
Animation fadeInAnimation = AnimationUtils.loadAnimation(con, R.anim.fade_in_anim);
registerLayout.startAnimation(fadeInAnimation);
registerLayout.setVisibility(View.VISIBLE);
}
});
titleLay.startAnimation(slide);
And that's the XML code of the R.anim.fade_in_anim-
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="500"/>
</set>
Edit: If I use other types of animations(fade out, slide etc...) it works fine, without flicking.
Thanks!
If you are using animateLayoutChanges in your layout file in combination with the animation onAnimationEnd toggling the View visibility it will result in two animations running and the view flashing or blinking. Setting view visibility causes the layouts animateLayoutChanges to run and to fade the view in once and then the animation you created causes a second animation to run as well.
Instead of setting the view's visibility, try to use the setAlpha function.
registerLayout.setAlpha(0f); //invisible
registerLayout.setAlpha(1f); //visible
Remove the declerations and initilizations from your onAnimationEnd, the initilization may take a long time since the XML needs to be parsed from resources,
put thouse two lines in your onCreate:
RelativeLayout registerLayout = (RelativeLayout) findViewById(R.id.registerLay);
Animation fadeInAnimation = AnimationUtils.loadAnimation(con, R.anim.fade_in_anim);
and set visibility to slide:
final TranslateAnimation slide = new TranslateAnimation(0, 0, 0,-100 );
slide.setDuration(500);
slide.setFillAfter(true);
slide.setAnimationListener(new
AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
registerLayout.startAnimation(fadeInAnimation);
registerLayout.setVisibility(View.VISIBLE);
}
});
titleLay.startAnimation(slide);
titleLay.setVisibilty(View.VISIBLE);
I'm having some troubles with a slideshow I'm building.
I've created 2 animations in xml for fade in and fade out:
fadein.xml
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="2000"/>
</set>
fadeout.xml
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="2000"/>
</set>
What Im'trying to do, is to change images from an ImageView using the fade effect, so the currently displayed image will fade out, and another one will fade in.
Considering that I have an image already set, I can fadeout this Image without problem, with this:
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.your_fade_in_anim);
imageView.startAnimation(fadeoutAnim);
But then, I set the next image to be displayed:
imageView.setImageBitmap(secondImage);
It just shows up in the imageView, and when i set the animation it hides the image, the fade it in... Is there any way to fix that, I mean, when I do imageView.setImageBitmap(secondImage); command, the image do not shows up immediately, and only when the fade in animation is executed?
I wanted to achieve the same goal as you, so I wrote the following method which does exactly that if you pass it an ImageView and a list of references to image drawables.
ImageView demoImage = (ImageView) findViewById(R.id.DemoImage);
int imagesToShow[] = { R.drawable.image1, R.drawable.image2,R.drawable.image3 };
animate(demoImage, imagesToShow, 0,false);
private void animate(final ImageView imageView, final int images[], final int imageIndex, final boolean forever) {
//imageView <-- The View which displays the images
//images[] <-- Holds R references to the images to display
//imageIndex <-- index of the first image to show in images[]
//forever <-- If equals true then after the last image it starts all over again with the first image resulting in an infinite loop. You have been warned.
int fadeInDuration = 500; // Configure time values here
int timeBetween = 3000;
int fadeOutDuration = 1000;
imageView.setVisibility(View.INVISIBLE); //Visible or invisible by default - this will apply when the animation ends
imageView.setImageResource(images[imageIndex]);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
fadeIn.setDuration(fadeInDuration);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
fadeOut.setStartOffset(fadeInDuration + timeBetween);
fadeOut.setDuration(fadeOutDuration);
AnimationSet animation = new AnimationSet(false); // change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
animation.setRepeatCount(1);
imageView.setAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(Animation animation) {
if (images.length - 1 > imageIndex) {
animate(imageView, images, imageIndex + 1,forever); //Calls itself until it gets to the end of the array
}
else {
if (forever){
animate(imageView, images, 0,forever); //Calls itself to start the animation all over again in a loop if forever = true
}
}
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
});
}
To implement this the way you have started, you'll need to add an AnimationListener so that you can detect the beginning and ending of an animation. When onAnimationEnd() for the fade out is called, you can set the visibility of your ImageView object to View.INVISIBLE, switch the images and start your fade in animation - you'll need another AnimationListener here too. When you receive onAnimationEnd() for your fade in animation, set the ImageView to be View.VISIBLE and that should give you the effect you're looking for.
I've implemented a similar effect before, but I used a ViewSwitcher with 2 ImageViews rather than a single ImageView. You can set the "in" and "out" animations for the ViewSwitcher with your fade in and fade out so it can manage the AnimationListener implementation. Then all you need to do is alternate between the 2 ImageViews.
Edit:
To be a bit more useful, here is a quick example of how to use the ViewSwitcher. I have included the full source at https://github.com/aldryd/imageswitcher.
activity_main.xml
<ViewSwitcher
android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inAnimation="#anim/fade_in"
android:outAnimation="#anim/fade_out" >
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="#drawable/sunset" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="#drawable/clouds" />
</ViewSwitcher>
MainActivity.java
// Let the ViewSwitcher do the animation listening for you
((ViewSwitcher) findViewById(R.id.switcher)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewSwitcher switcher = (ViewSwitcher) v;
if (switcher.getDisplayedChild() == 0) {
switcher.showNext();
} else {
switcher.showPrevious();
}
}
});
Have you thought of using TransitionDrawable instead of custom animations?
https://developer.android.com/reference/android/graphics/drawable/TransitionDrawable.html
One way to achieve what you are looking for is:
// create the transition layers
Drawable[] layers = new Drawable[2];
layers[0] = new BitmapDrawable(getResources(), firstBitmap);
layers[1] = new BitmapDrawable(getResources(), secondBitmap);
TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
imageView.setImageDrawable(transitionDrawable);
transitionDrawable.startTransition(FADE_DURATION);
I used used fadeIn animation to replace new image for old one
ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();
you can do it by two simple point and change in your code
1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal
2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible
fadeout.xml
<alpha
android:duration="4000"
android:fromAlpha="1.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
fadein.xml
<alpha
android:duration="6000"
android:fromAlpha="0.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
In you java class
Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
iv.setVisibility(View.VISIBLE);
iv2.setVisibility(View.GONE);
animFadeOut.reset();
iv.clearAnimation();
iv.startAnimation(animFadeOut);
Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
iv2.setVisibility(View.VISIBLE);
animFadeIn.reset();
iv2.clearAnimation();
iv2.startAnimation(animFadeIn);
For infinite Fade In and Out
AlphaAnimation fadeIn=new AlphaAnimation(0,1);
AlphaAnimation fadeOut=new AlphaAnimation(1,0);
final AnimationSet set = new AnimationSet(false);
set.addAnimation(fadeIn);
set.addAnimation(fadeOut);
fadeOut.setStartOffset(2000);
set.setDuration(2000);
imageView.startAnimation(set);
set.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) { }
#Override
public void onAnimationRepeat(Animation animation) { }
#Override
public void onAnimationEnd(Animation animation) {
imageView.startAnimation(set);
}
});
I'm using this kind of routine for programmatically chaining animations.
final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
anim_out.setAnimationListener(new AnimationListener()
{
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation)
{
////////////////////////////////////////
// HERE YOU CHANGE YOUR IMAGE CONTENT //
////////////////////////////////////////
//ui_image.setImage...
anim_in.setAnimationListener(new AnimationListener()
{
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {}
});
ui_image.startAnimation(anim_in);
}
});
ui_image.startAnimation(anim_out);
The best and the easiest way, for me was this..
->Simply create a thread with Handler containing sleep().
private ImageView myImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
myImageView.startAnimation(myFadeInAnimation);
new Thread(new Runnable() {
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.w("hendler", "recived");
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout);
myImageView.startAnimation(myFadeOutAnimation);
myImageView.setVisibility(View.INVISIBLE);
}
};
#Override
public void run() {
try{
Thread.sleep(2000); // your fadein duration
}catch (Exception e){
}
handler.sendEmptyMessage(1);
}
}).start();
}
This is probably the best solution you'll get. Simple and Easy. I learned it on udemy.
Suppose you have two images having image id's id1 and id2 respectively and currently the image view is set as id1 and you want to change it to the other image everytime someone clicks in. So this is the basic code in MainActivity.java File
int clickNum=0;
public void click(View view){
clickNum++;
ImageView a=(ImageView)findViewById(R.id.id1);
ImageView b=(ImageView)findViewById(R.id.id2);
if(clickNum%2==1){
a.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
else if(clickNum%2==0){
b.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
}
I hope this will surely help