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()
}
Related
I am trying to write an animation like in WhatsApp Call screen. But I don't know what is the true way to achieve this.
To achieve this animation I am starting trying with fadein and fadeout animation. These are my set methods for fade in and out animations.
private Animation setAnimFadeOut(int startOff,int duration){
Animation animFadeOut;
animFadeOut = new AlphaAnimation(1, 0);
animFadeOut.setInterpolator(new AccelerateInterpolator());
animFadeOut.setStartOffset(startOff);
animFadeOut.setDuration(duration);
return animFadeOut;
}
private Animation setAnimFadeIn(int startOff,int duration){
Animation animFadeIn;
animFadeIn = new AlphaAnimation(0, 1);
animFadeIn.setInterpolator(new AccelerateInterpolator());
animFadeIn.setStartOffset(startOff);
animFadeIn.setDuration(duration);
return animFadeIn;
}
and for every animations animationlisteners onAnimationEnd method triggers animation for restart. fadeIn animation starts fadeOut animation and fadeOut starts fadeIn animation.
right1FadeOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
right1.startAnimation(right1FadeIn);
Log.i(TAG, "onAnimationEnd: 1 outEnd");
}
});
right1FadeIn.setAnimationListener(new Animation.AnimationListener() {
Override
public void onAnimationEnd(Animation animation) {
right1.startAnimation(right1FadeOut);
Log.i(TAG, "onAnimationEnd: 1 inEnd");
}
});
Initialization
int startOff = 0;
int diff = 100;
int duration = 600;
final Animation right1FadeOut = setAnimFadeOut(startOff,duration);
final Animation right1FadeIn = setAnimFadeIn(0,duration);
final Animation right2FadeOut = setAnimFadeOut(startOff+diff,duration+diff);
final Animation right2FadeIn = setAnimFadeIn(0,duration);
final Animation right3FadeOut = setAnimFadeOut(startOff+diff*2,duration+diff*2);
final Animation right3FadeIn = setAnimFadeIn(0,duration);
I am starting animation calling fadeout for every button and it did not work as I expected. How can I achieve animation like WhatsApp?
right1.startAnimation(right1FadeOut);
right2.startAnimation(right2FadeOut);
right3.startAnimation(right3FadeOut);
this is the result.
I would first use Animator objects instead of Animation, then i can use AnimatorSet to control all animators as a group. (aka: order)
For example:
activity XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0"
android:src="#drawable/ic_launcher_foreground" />
<ImageView
android:id="#+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0"
android:src="#drawable/ic_launcher_foreground" />
<ImageView
android:id="#+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0"
android:src="#drawable/ic_launcher_foreground" />
<ImageView
android:id="#+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0"
android:src="#drawable/ic_launcher_foreground" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Activity Class:
Java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View[] images = {findViewById(R.id.img1), findViewById(R.id.img2), findViewById(R.id.img3), findViewById(R.id.img4),}; //array of views that we want to animate
//we will have 2 animator foreach view, fade in & fade out
//prepare animators - creating array of animators & instantiating Object animators
ArrayList<ObjectAnimator> anims = new ArrayList<>(images.length * 2);
for (View v : images) anims.add(ObjectAnimator.ofFloat(v, View.ALPHA, 0f, 1f).setDuration(80)); //fade in animator
for (View v : images) anims.add(ObjectAnimator.ofFloat(v, View.ALPHA, 1f, 0f).setDuration(80)); //fade out animator
final AnimatorSet set = new AnimatorSet(); //create Animator set object
//if we want to repeat the animations then we set listener to start again in 'onAnimationEnd' method
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
set.start(); //repeat animator set indefinitely
}
});
set.setStartDelay(600); //set delay every time we start the chain of animations
for (int i = 0; i < anims.size() - 1; i++) set.play(anims.get(i)).before(anims.get(i + 1)); //put all animations in set by order (from first to last)
findViewById(R.id.txt).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //start the animations on click
set.start();
}
});
}
}
Kotlin:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val images = arrayOf(img1, img2, img3, img4) //array of views that we want to animate
//we will have 2 animator foreach view, fade in & fade out
//prepare animators - creating array of animators & instantiating Object animators
val anims = ArrayList<ObjectAnimator>(images.size * 2)
for (v in images) anims.add(ObjectAnimator.ofFloat(v, View.ALPHA, 0f, 1f).setDuration(80)) //fade in animator
for (v in images) anims.add(ObjectAnimator.ofFloat(v, View.ALPHA, 1f, 0f).setDuration(80)) //fade out animator
val set = AnimatorSet() //create Animator set object
//if we want to repeat the animations then we set listener to start again in 'onAnimationEnd' method
set.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) = set.start() //repeat animator set indefinitely
})
set.startDelay = 600 //set delay every time we start the chain of animations
for (i in 0 until anims.size - 1) set.play(anims[i]).before(anims[i + 1]) //put all animations in set by order (from first to last)
txt.setOnClickListener { set.start() } //start the animations on click
}
}
Try to start your subsequent animations in your AnimationListeners onAnimationStart method with an increasing delay.
arrow1FadeIn.setAnimationListener( new Animation.AnimationListener() {
#Override
public void onAnimationStart( Animation animation )
{
arrow2.startAnimation( arrow2FadeIn );
}
#Override
public void onAnimationEnd( Animation animation )
{
arrow1.startAnimation( arrow1FadeOut );
}
#Override
public void onAnimationRepeat( Animation animation )
{
}
} );
arrow1FadeOut.setAnimationListener( new Animation.AnimationListener()
{
#Override
public void onAnimationStart( Animation animation )
{
}
#Override
public void onAnimationEnd( Animation animation )
{
arrow1.startAnimation( arrow1FadeIn );
}
#Override
public void onAnimationRepeat( Animation animation )
{
}
} );
And your animations like
final Animation arrow1FadeIn = setAnimFadeIn( startOff, duration );
final Animation arrow1FadeOut = setAnimFadeOut( startOff, duration );
final Animation arrow2FadeIn = setAnimFadeIn( diff, duration );
final Animation arrow2FadeOut = setAnimFadeOut( startOff, duration );
final Animation arrow3FadeIn = setAnimFadeIn( diff*2, duration );
final Animation arrow3FadeOut = setAnimFadeOut( startOff, duration );
You may need to twiddle a bit when starting all over again but this way, they should be in sync. Just start the first fadeIn Animation with
arrow1.startAnimation( arrow1FadeIn );
I suggest you use Facebook Rebound library.
It support Spring animation like facebook has. It also has cool feature called SpringChain, which automatically play a sequence of animation using Spring physics from start to end. You can custom how you want to animate the View (scale, alpha, translate ...)
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()
Android Studio 1.5
Device Samsung 4.4.2
I am trying to animate items loaded from a ArrayList into a recyclerview. I when the dropdown arrow is clicked the items should animate (decelerate) when expanded and should animate when collapsed. However, currently the list items just appears.
Code that calls the setAnimation
#Override
public void onBindChildViewHolder(ChatChildViewHolder childViewHolder, int position, Object childListItem) {
ChatChildTitles chatChildTitles = (ChatChildTitles)childListItem;
childViewHolder.tvChildTitle.setText(chatChildTitles.getTitle());
setAnimation(childViewHolder.cvChildRooms, position);
}
Code for setting the animation
private void setAnimation(CardView viewToAnimate, int position) {
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in);
animation.setInterpolator(mContext, android.R.anim.decelerate_interpolator);
viewToAnimate.startAnimation(animation);
}
Here is a couple of screenshots:
In the collapsed state
After the arrow has been clicked expland the list
This is my layout I am using that represents the rows that will be displayed in the recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/cvChildRooms"
xmlns:card="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card:cardBackgroundColor="#color/child_header_lighter_grey"
card:contentPadding="4dp"
card:cardPreventCornerOverlap="true">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical|start"
android:src="#drawable/photorace"/>
<TextView
android:id="#+id/tvChildTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center"
android:text="Coffee Latte Room"
android:fontFamily="sans-serif-light"
android:textSize="16sp"
android:textColor="#android:color/black"/>
</android.support.v7.widget.CardView>
I have a function that should start the animation.
private void setAnimation(CardView viewToAnimate, int position) {
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.decelerate_interpolator);
viewToAnimate.startAnimation(animation);
}
I have tested using the following that works ok with slide_in_left. However, I don't want them to slide in from the left
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
Many thanks for any suggestions,
If you want to use a decelerate interpolator you need to set it AS an interpolator, not as the animator:
private void setAnimation(CardView viewToAnimate, int position) {
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in); //change this with your desidered (or custom) animation
animation.setInterpolator(mContext, android.R.anim.decelerate_interpolator);
viewToAnimate.startAnimation(animation);
}
UPDATE
You said that you are using com.bignerdranch.android:expandablerecyclerview:2.0.3.
From the official docs of the library, it's clearly state how to create expand/collapse animations:
You can also create your own animations for expansion by overriding
ParentViewHolder#onExpansionToggled(boolean), which will be called for
you when the itemView is expanded or collapsed.
I suggest you to take a look at the official example of the library.
You can't use decelerate_interpolator because it's not an animation, it is an interpolator:
An interpolator defines the rate of change of an animation. This
allows the basic animation effects (alpha, scale, translate, rotate)
to be accelerated, decelerated, repeated, etc.
Reference:
http://developer.android.com/reference/android/view/animation/Interpolator.html
As you can see the XML that describing them are completely different:
Source of decelerate_interpolator.xml:
<decelerateInterpolator />
Source of slide_in_left.xml:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-50%p" android:toXDelta="0"
android:duration="#android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="#android:integer/config_mediumAnimTime" />
</set>
To animate the list as they expand and collapse, consider using an ItemAnimator from android.
You will need to set up a custom itemAnimator, something similar to the one in the link below:
https://gist.github.com/ademar111190/dc988c8d899dae0193f7
Set the itemAnimator in the method runPendingAnimations to your decelerate interpolator.
#Override
public void runPendingAnimations() {
if (!mViewHolders.isEmpty()) {
int animationDuration = 300;
AnimatorSet animator;
View target;
for (final RecyclerView.ViewHolder viewHolder : mViewHolders) {
target = viewHolder.itemView;
target.setPivotX(target.getMeasuredWidth() / 2);
target.setPivotY(target.getMeasuredHeight() / 2);
animator = new AnimatorSet();
animator.playTogether(
ObjectAnimator.ofFloat(target, "translationX", -target.getMeasuredWidth(), 0.0f),
ObjectAnimator.ofFloat(target, "alpha", target.getAlpha(), 1.0f)
);
animator.setTarget(target);
animator.setDuration(animationDuration);
animator.setInterpolator(new DecelerateInterpolator());
animator.setStartDelay((animationDuration * viewHolder.getPosition()) / 10);
animator.addListener(new AnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
mViewHolders.remove(viewHolder);
}
});
animator.start();
}
}
}
Then you will need to set the itemAnimator to the recycler view.
recyclerView.setItemAnimator(new MyItemAnimator());
You can use below code for do that.
private void hideViews() {
recyclerView.animate().translationY(-recyclerView.getHeight()).setInterpolator(new AccelerateInterpolator(2));
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight()+fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
private void showViews() {
recyclerView.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}
You can call this method onClick of your Button.
Hope it will help you.
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
I want to be able to do a text animation and change the size of the text in a TextView. I read that there are property animations in android but if someone knows a simple code that can do this for me or an example somewhere I will deeply appreciate it. Thank u in advance!
scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="2.0"
android:toYScale="2.0"
android:duration="3000"></scale>
</set>
A function into an Activity:
private void RunAnimation()
{
Animation a = AnimationUtils.loadAnimation(this, R.anim.scale);
a.reset();
TextView tv = (TextView) findViewById(R.id.firstTextView);
tv.clearAnimation();
tv.startAnimation(a);
}
extracted and modified from here
Animation animation=new TranslateAnimation(0,480,0,0);
animation.setDuration(5000);
animation.setRepeatMode(Animation.RESTART);
animation.setRepeatCount(Animation.INFINITE);
text.startAnimation(animation);
// applying animation to textview object..
If you are using button event to show animation then put the code inside onClick() otherwise use override method onWindowFocusChanged(boolean hasFocus) to start animation
Use ValueAnimator class in the android
final float startSize = o; // Size in pixels
final float endSize = 30;
final int animationDuration = 1000; // Animation duration in ms
ValueAnimator animator = ValueAnimator.ofFloat(startSize, endSize);
animator.setDuration(animationDuration);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedValue = (float) valueAnimator.getAnimatedValue();
tv.setTextSize(animatedValue);
}
});
animator.start();
refer this link ValueAnimator
Another solution is that apply scale animation on Textview or its parent layout
ScaleAnimation scaleAnimation = new ScaleAnimation(0.7f, 1.1f, 0.7f, 1.1f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(600);
viewZoom.startAnimation(scaleAnimation);