android animatorset memory management, freeing up memory from imageview - android

I have a repeating AnimatorSet that uses a sequence of full frame images on several different activities. I'm getting an out of memory exception as it seems that the imageviews are taking up too much memory.
Originally the activities in the background still had their animations running in a loop taking up memory. I tried remedying by creating and ending animations on pause/resume so that memory from animations in the non-foreground views are reclaimed but I think I need to do more to clear out the imageviews from memory as well.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_face_o_matic_start);
getActionBar().hide();
}
#Override
protected void onResume() {
super.onResume();
createAnimations();
}
#Override
protected void onPause() {
super.onPause();
this.mAnimatorSet.removeAllListeners();
this.mAnimatorSet.end();
//TODO: clear and free up the memory from the image views somehow
// this is the part I need help with I think
}
protected ObjectAnimator getGlowAnimation(View v, int duration){
ObjectAnimator animation = ObjectAnimator.ofFloat(v, "alpha", 0f, 1f);
animation.setDuration(duration);
animation.setRepeatCount(1);
animation.setRepeatMode(Animation.REVERSE);
return animation;
}
public void createAnimations(){
//TODO: destroy these imageviews to reclaim memory on pause
// originally had them in on create but the imageviews continued to
// take up memory when the activity went into the background
/*start animations */
final ImageView bg1 = (ImageView) findViewById(R.id.bg_face_o_matic_1);
final ImageView bg2 = (ImageView) findViewById(R.id.bg_face_o_matic_2);
final ImageView bg3 = (ImageView) findViewById(R.id.bg_face_o_matic_3);
final ImageView bg4 = (ImageView) findViewById(R.id.bg_face_o_matic_4);
final ImageView bg5 = (ImageView) findViewById(R.id.bg_face_o_matic_5);
final ImageView bg6 = (ImageView) findViewById(R.id.bg_face_o_matic_6);
ObjectAnimator anim1 = getGlowAnimation(bg1, 400);
ObjectAnimator anim2 = getGlowAnimation(bg2, 400);
ObjectAnimator anim3 = getGlowAnimation(bg3, 400);
ObjectAnimator anim4 = getGlowAnimation(bg4, 400);
ObjectAnimator anim5 = getGlowAnimation(bg5, 400);
ObjectAnimator anim6 = getGlowAnimation(bg6, 400);
List<Animator> animations = new ArrayList<Animator>(Arrays.asList(anim1, anim2, anim3, anim4, anim5, anim6));
mAnimatorSet.playSequentially(animations);
//loop the animator set
mAnimatorSet.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimatorSet.start();
}
});
mAnimatorSet.start();
/*end animations */
}

Everytime your application enters this Activity it calls your onResume() method, in which it calls createAnimations(), hence it is continuously creating lots of images and other stuff. You should declare some stuff outside of this method, declare them on class-level and init them in onCreate() so it will be much more efficient. I reduced your createAnimations() a bit. And just call this method once in your onCreate() after you initialize its necessary dependency variables and in your onResume() just call mAnimatorSet.playSequentially(animations);
public void createAnimations(){
mAnimatorSet.playSequentially(animations);
//loop the animator set
mAnimatorSet.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnimatorSet.start();
}
});
}

Related

No Rotation in image using rotate Animation

Using Rotate Animation in android, but no rotation in image after clicking the button.
public class MainActivity extends AppCompatActivity {
ImageView spinImage;
Button buton;
Random r;
int degree =0 , degreeold= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button) findViewById(R.id.spinbutton);
spinImage= (ImageView) findViewById(R.id.spinimage);
r= new Random();
buton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
degreeold = degree % 360;
degree = r.nextInt(3600)+720;
degree= 4400;
RotateAnimation rotate = new RotateAnimation( degreeold, degree,
RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF , 0.5f);
rotate.setDuration(3600);
rotate.setFillAfter(true);
rotate.setInterpolator( new DecelerateInterpolator());
rotate.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
spinImage.setAnimation(rotate);
}
});
}
i am not able to find the mistake why there is no rotation in image. there is no error while running and app open without any delay but there is no animation when clicking the button.
You haven't started the animation. Try to use spinImage.startAnimation(rotate);
setAnimation is meant to give you more fine grained control if you want to start the animation delayed or together with other animations.
From the documentation:
Sets the next animation to play for this view. If you want the animation to play immediately, use startAnimation(android.view.animation.Animation) instead. This method provides allows fine-grained control over the start time and invalidation, but you must make sure that 1) the animation has a start time set, and 2) the view's parent (which controls animations on its children) will be invalidated when the animation is supposed to start.
Replace spinImage.setAnimation(rotate); with spinImage.startAnimation(rotate);

How to make an imageView change background randomly?

I have an imageview with 5 backgrounds to choose from. I want to fade image2 out and set image5 as background with fade in effect. This should keep changing randomly. The problem is, how do i do this efficiently?
this is how i give fade in and fade out effects using system animations-
fade out
Animation out = AnimationUtils.makeOutAnimation(this, true);
viewToAnimate.startAnimation(out);
viewToAnimate.setVisibility(View.INVISIBLE);
fade in
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
viewToAnimate.startAnimation(in);
viewToAnimate.setVisibility(View.VISIBLE);
this is how i change my background-
search_engine_identifier.setImageResource(R.drawable.ic_yahoo);
Create two in xml you can get from here then load them like this.
ImageView myImageView = (ImageView) findViewById(R.id.imageView2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Splash.this, R.anim.fadein)
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(Splash.this, R.anim.fadeout);
int value = 0; // Global Type
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(value%2 == 0){
doFadeOutAnimation();
}else{
doFadeInAnimation();
}
value ++;
}
});
Another way to do this is by using one of Android's View Animator classes, such as ObjectAnimator. Here's what I'm doing:
1) Add the drawable ID's of the images you want to use into an int array.
2) Create ObjectAnimators for the fadeIn and fadeOut animations. You can set the duration of the fade in and fade out to whatever you want.
3) Add an AnimatorListener to the fadeOut ObjectAnimator so that when it finishes, it will set the new image (which is chosen randomly by selecting a random number from the images array) and then it will fade back in with the new image, using the fadeIn ObjectAnimator.
4) Create a runnable and in it's run method, start the fadeOut animation.
5) Call handler.postDelayed on the runnable and use that to decide how long you want each image to stay before fading out.
6) At the end of your Runnable's run method, call handler.postDelayed again so the images will continue to fade in and out, but you should make sure that you have some kind of conditional statement so that you can stop the animation when you need to, which is why I used the boolean "running" so I can set it to false when I need to stop the handler from looping.
ImageView mImageView = (ImageView) findViewById(R.id.imageView);
boolean running = true;
final int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5};
final Random random = new Random();
final Handler handler = new Handler();
final ObjectAnimator fadeIn = ObjectAnimator.ofFloat(mImageView, "alpha", 0f, 1f);
fadeIn.setDuration(1000);
final ObjectAnimator fadeOut = ObjectAnimator.ofFloat(mImageView, "alpha", 1f, 0f);
fadeOut.setDuration(1000);
fadeOut.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
int rand = random.nextInt(images.length);
mImageView.setImageResource(images[rand]);
fadeIn.start();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
Runnable runnable = new Runnable() {
#Override
public void run() {
fadeOut.start();
if (running) {
handler.postDelayed(this, 5000);
}
}
};
handler.postDelayed(runnable, 5000);
}
This will continuously loop through your selected images (randomly) with fade in/ fade out animations. You can add a few checks to make sure the same image doesn't appear twice in a row, etc.

How to do smooth transition from one image to another

I have an activity where I am changing the ImageView periodically, for that I wrote the below line of code .
imageview.setImageUri(resId);
I am increasing the resource id .It works fine but there is sudden transition from one image to another. I don't want that,I want the smooth transition of image view to another image. How can i do that?
Try this
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 == true){
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
}
});
}
Try alpha animation. First fadeout the imageview, on animation end, change the resource and then fadein the imageview.
For a smooth transition you must use Animations in Android, start by reading the following link:
http://www.vogella.com/articles/AndroidAnimation/article.html
There are many similar questions on stackoverflow about animations and many tutorials are available on the net about this topic. A simple search on google will bring you tons of result

How do I stop an infinite animation on an ImageView, but let it complete its current cycle?

I applied an infinite animation on an ImageView to indicate a running background thread in my app. When the thread finishes, I'm able to stop the animation by using clearAnimation(), but it snaps the ImageView back to its starting position, and I'd like the current animation cycle to complete (which is designed to gracefully end in its starting position). Is there a way to do this?
Register an AnimationListener, and wait until onAnimationRepeat() to clear it. I haven't tried this, but I think it will work.
Just call setRepeatCount(0) and then listen for onAnimationEnd. See here for more details.
You can set the desirable position of your animation in the onAnimationEnd() method of your animation listener. Then, instead of going to the initial position, the View will be displayed at the coordinates you set up there.
animation = new TranslateAnimation(0, -length, 0, 0); //setup here your translation parameters
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(10);
animation.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
animationRunning = true;
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
animationRunning = false;
// setAnimationPositionAfterPositionChange();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) runningText.getLayoutParams();
params.leftMargin = currentPosition; //Calculate you current position here
runningText.setLayoutParams(params);
}
});
runningText.setAnimation(animation);
If you are using animate()
you use setListener(null) to stop it the animation,
works for me.
image.animate()
.translationXBy(-width* 0.5f)
.setDuration(300)
.setStartDelay(6000)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
image.animate().rotationBy(90).setDuration(1000).setStartDelay(1).setListener(null);
}
});

Applying successive animations to ImageView in Android

I would like to apply successive animations (say ScaleAnimation) to an ImageView showing a resource image. The animation is triggered by a button. For example, I would like to incrementally enlarge an image upon each button click.
I've set fillAfter="true" on the animation. However, all the animations start from the original state of the ImageView. It seems as if the ImageView resets its state and the animation is always the same, instead of starting from the final state of the previous animation.
What am I doing wrong?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
animate();
}});
}
private void animate() {
ImageView imageView = (ImageView) findViewById(R.id.ImageView01);
ScaleAnimation scale = new ScaleAnimation((float)1.0, (float)1.5, (float)1.0, (float)1.5);
scale.setFillAfter(true);
scale.setDuration(500);
imageView.startAnimation(scale);
}
It seems as if the ImageView resets
its state and the animation is always
the same, instead of starting from the
final state of the previous animation.
Precisely! I'm sure there's a use for fillAfter="true", but I haven't figured out the point for it yet.
What you need to do is set up an AnimationListener on each Animation of relevance, and do something in the listener's onAnimationEnd() to actually persist the end state of your animation. I haven't played with ScaleAnimation so I'm not quite sure what the way to "persist the end state" would be. If this were an AlphaAnimation, going from 1.0 to 0.0, you would make the widget INVISIBLE or GONE in onAnimationEnd(), for example.
I've had the same problem and created the following code to easily use different animations. It only supports translation and alpha levels for now as I haven't used scaling, but could easily be extended to support more features.
I reset the scroll and the visibility before starting the animation, but that's just because I needed on/off animations.
And the "doEnd" boolean is there to avoid a stack overflow on the recursion (scrollTo calls onAnimationEnd for some obscure reason...)
private void setViewPos(View view, Animation anim, long time){
// Get the transformation
Transformation trans = new Transformation();
anim.getTransformation(time, trans);
// Get the matrix values
float[] values = new float[9];
Matrix m = trans.getMatrix();
m.getValues(values);
// Get the position and apply the scroll
final float x = values[Matrix.MTRANS_X];
final float y = values[Matrix.MTRANS_Y];
view.scrollTo(-(int)x, -(int)y);
// Show/hide depending on final alpha level
if (trans.getAlpha() > 0.5){
view.setVisibility(VISIBLE);
} else {
view.setVisibility(INVISIBLE);
}
}
private void applyAnimation(final View view, final Animation anim){
view.scrollTo(0, 0);
view.setVisibility(VISIBLE);
anim.setAnimationListener(new AnimationListener(){
private boolean doEnd = true;
#Override
public void onAnimationEnd(Animation animation) {
if (doEnd){
doEnd = false;
setViewPos(view, animation, anim.getStartTime() + anim.getDuration());
}
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationStart(Animation animation) {
}
});
view.startAnimation(anim);
}

Categories

Resources