Animation on image resource change - android

I am trying to change repeatedly images in image view (it doesn't matter what component to use). I need to change background image each N seconds.
I have tried to use Animation drawable declaring images in xml file.
It works, but I don't know to apply any effect to it, like fade in,blur or something other.
So my task is to change periodically background image with transition effect.
Please suggest how to deal with this problem, I would be very grateful for any help.

I used an image switcher to switch images in regular intervals
xml part
<ImageSwitcher
android:id="#+id/smsimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/defaultimage" />
class code was like this
private final int[] images = { R.drawable.vava, R.drawable.vavaone,R.drawable.vavatwo,R.drawable.vavathree,R.drawable.vavafour,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
img=(ImageSwitcher)findViewById(R.id.smsimg);
startAnimatedBackground();
private void startAnimatedBackground() {
Animation aniIn = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
aniIn.setDuration(3000);
Animation aniOut = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
aniOut.setDuration(3000);
final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.smsimg);
imageSwitcher.setInAnimation(aniIn);
imageSwitcher.setOutAnimation(aniOut);
imageSwitcher.setFactory(this);
imageSwitcher.setImageResource(images[index]);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (isRunning) {
index++;
index = index % images.length;
Log.d("Intro Screen", "Change Image " + index);
imageSwitcher.setImageResource(images[index]);
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, interval);
}

Related

How to correctly animate stacking views one after another in Android using handler?

I have a LinearLayout with RelativeLayout children. Each RelativeLayout has a background image like a file cabinet. I am trying to animate the drawers dropping down into view one after another with a smooth delay. Everything I have tried plays all animations at once. I have this as my method for animating each drawer:
private void dropAndPause(final RelativeLayout drawer){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_down);
animation.setStartOffset(750L);
drawer.startAnimation(animation);
}
}, 1200);
}
I have also tried this:
View[] views = new View[] { ... };
// 100ms delay between Animations
long delayBetweenAnimations = 100l;
for(int i = 0; i < views.length; i++) {
final View view = views[i];
// We calculate the delay for this Animation, each animation starts 100ms
// after the previous one
int delay = i * delayBetweenAnimations;
view.postDelayed(new Runnable() {
#Override
public void run() {
Animation animation = AnimationUtils.loadAnimation(context, R.anim.your_animation);
view.startAnimation(animation);
}
}, delay);
}
Instead of View[] views, I used this:
View[] drawers = new View[] {
drawerOne, drawerTwo, drawerThree, drawerFour, drawerFive
};
Which plays, again, all of the animations at once. How can I get each "drawer"/view to slide in one at a time? Also, should I have each view as visibility GONE initially?
If you want to animate the views inside a layout, then it's much easier to use layout animations. Basically, you need to load an animation, create a LayoutAnimationController, set the delay on it, and launch the animation. Here's some sample code.
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_down);
animation.setStartOffset(750L);
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.1F);
viewGroup.setLayoutAnimation(controller);
viewGroup.startLayoutAnimation();
The delay here is set as fraction of the animation duration.

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.

Colors "flowing" in Android background

I have an application and I want to set it's background just like the Instagram's login page, the one with that "gradient colors". The colors are "moving" and it creats a cool effect. This is what I've tried so far:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_one);
colorFul = (RelativeLayout) findViewById(R.id.background);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[] {a,b});
gd.setCornerRadius(0f);
colorFul.setBackgroundDrawable(gd);
for(int i = 0; i<6; i++){
if(a == 0xff000000){
a = 0xff00ffff;
b = 0xff444444;
}else if(a == 0xff00ffff){
a = 0xff888888;
b = 0xff00ff00;
}else if(a == 0xff888888){
a = 0xffcccccc;
b = 0xffff00ff;
}else if(a==0xffcccccc){
a = 0xffff0000;
b = 0xffffffff;
}else if(a==0xffff0000){
a = 0xffffffff;
b = 0xffffff00;
}
System.out.println("||");
SystemClock.sleep(1000);
System.out.println(">");
}
}
But this doesn't work. What happens is that the collors don't change, it remains black until it gets to the last if and then the background become white and yellow(that are, respectively, the collors 0xffffffff and 0xffffff00), in gradient shape.
So, how can I do it? I don't care how it's done. Whether it is with GradientDrawable or using an animated gif as background(which didn't work, the gif remained still) or any other way. Thanks.
(This is what I want, the gif isn't that good but you can see how the background is changing it's color)
You could programmatically create something that changes the level of gradient over time, but that would require some effort. Alternatively, you could use a TransitionDrawable to fade between different gradients, which should produce a similar effect.
This can be implemented as follows:
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<!-- use two gradients, extending from opposite sides of the page-->
<item android:drawable="#drawable/gradientLeft" />
<item android:drawable="#drawable/gradientRight" />
</transition>
Then, you can activate the transition in code as follows:
TransitionDrawable transition = (TransitionDrawable) myLayout.getBackground();
transition.startTransition(1500);
Obviously you'll probably need to spend some time to get it looking the way you want, but this would be far easier than hard-coding a transitional algorithm!
COMPLETE AND WORKING CODE BELOW
So, I got my idea implemented, and it looks awesome! I didn't expect it would look this nice, but it's really cool. I was bored so decided I would shove the whole thing into a function so it's easier for you (and others) to utilize.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.background);
Drawable backgrounds[] = new Drawable[3];
backgrounds[0] = ContextCompat.getDrawable(this, R.drawable.gradient1);
backgrounds[1] = ContextCompat.getDrawable(this, R.drawable.gradient2);
backgrounds[2] = ContextCompat.getDrawable(this, R.drawable.gradient3);
Crossfade(image, backgrounds, 10000);
}
public void Crossfade(final ImageView image, final Drawable layers[], final int speedInMs) {
class BackgroundGradientThread implements Runnable {
Context mainContext;
TransitionDrawable crossFader;
boolean first = true;
BackgroundGradientThread(Context c) {
mainContext = c;
}
public void run() {
Handler mHandler = new Handler(mainContext.getMainLooper());
boolean reverse = false;
while (true) {
if (!reverse) {
for (int i = 0; i < layers.length - 1; i++) {
Drawable tLayers[] = new Drawable[2];
tLayers[0] = layers[i];
tLayers[1] = layers[i + 1];
final TransitionDrawable tCrossFader = new TransitionDrawable(tLayers);
tCrossFader.setCrossFadeEnabled(true);
Runnable transitionRunnable = new Runnable() {
#Override
public void run() {
image.setImageDrawable(tCrossFader);
tCrossFader.startTransition(speedInMs);
}
};
mHandler.post(transitionRunnable);
try {
Thread.sleep(speedInMs);
} catch (Exception e) {
}
}
reverse = true;
}
else if (reverse) {
for (int i = layers.length - 1; i > 0; i--) {
Drawable tLayers[] = new Drawable[2];
tLayers[0] = layers[i];
tLayers[1] = layers[i - 1];
final TransitionDrawable tCrossFader = new TransitionDrawable(tLayers);
tCrossFader.setCrossFadeEnabled(true);
Runnable transitionRunnable = new Runnable() {
#Override
public void run() {
image.setImageDrawable(tCrossFader);
tCrossFader.startTransition(speedInMs);
}
};
mHandler.post(transitionRunnable);
try {
Thread.sleep(speedInMs);
} catch (Exception e) {
}
}
reverse = false;
}
}
}
}
Thread backgroundThread = new Thread(new BackgroundGradientThread(this));
backgroundThread.start();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/gradient2"
android:scaleType="fitXY"/>
<TextView android:text="Hello World!" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
gradient1/2.jpg
The primary function here creates a new thread that will automatically begin shifting the two images back and forth. Once one full transition has completed, it will then begin to fade back into the original image. It creates a really smooth and flowy effect most of the time, but may look weird when combining some gradient drawables. The function looks like this:
public void Crossfade(final ImageView image, final Drawable layers[], final int speedInMs)
1) final ImageView image
The first parameter should be the image object that is going to represent your background.
2) final Drawable layers[]
The second parameter takes an array of drawables, which should be two images like the ones I showed above. Playing around with different gradient images is fun, and quite interesting to watch how colors "flow". Be careful with your image sizes, though, as I had initially used massive images that had crashed the app or stuttered terribly in the animation process.
3) final int speedInMs
The last parameter simply represents the time (in milliseconds) it will take to completely transition from the first drawable to the second.
Here's a GIF of the result of these two images crossfading with a speed of 5000ms (note: I couldn't put a 10 second GIF on here showing the whole transition, but it's quite smooth!):
Github Link To Repository
EDIT 2: I updated the Github and the function on here, but I just added in multi-drawable support so an array of any number of images can be added in and it will cycle through them chronologically, until reaching the end at which point it will reverse through and repeat. Sexy.

how to apply many rotate translate,scale animation to imageview in android

Hi am doing one application here when my activity starts that time i need to rotate image first then i need to move image from top to center there i have to scale my image after some time i have to in visable my imageview,i tried using below code first i applied rotate animation then i applied translate animation.after 2 seconds i applied scale animation but image is not scaling in center its taking imagview original postion(top) there its scaling but i need to scale imageview after move animation where is there at that postion i need scale image view...any one suggest how to apply different animations to single imageview.
public class A extends Activity{
TranslateAnimation moveLefttoRight1;
Animation logoMoveAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
final ImageView myImage = (ImageView)findViewById(R.id.imageView1);
//rotate animation
final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
myImage.startAnimation(myRotation);
//translate animation
moveLefttoRight1 = new TranslateAnimation(0, 0, 0, 200);
moveLefttoRight1.setDuration(2000);
moveLefttoRight1.setFillAfter(true);
myImage.startAnimation(moveLefttoRight1);
//scale animation
logoMoveAnimation = AnimationUtils.loadAnimation(this, R.anim.sacle);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
myImage.startAnimation(logoMoveAnimation);
}
}, 2000);
}
}
Use Animation listener.
when get animation end start another animation.
for better reference
http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html
http://www.techrepublic.com/blog/android-app-builder/how-to-use-android-animation-listeners/

Android ImageView changing alpha Animation

I have four images that need loaded. I want one animation to play, wait 500ms, another one play, wait 500ms, etc.. All the animation does is change the alpha from 255 to 0 and then back to 255. All four imageViews need that animation.
I am having two problems currently.
1.) All of the images play at the same time.
2.) The next time the method is called, the animations don't work.
public void computerLights()
{
ImageView green = (ImageView)findViewById(R.id.imgViewGreen);
ImageView red = (ImageView)findViewById(R.id.imgViewRed);
ImageView blue = (ImageView)findViewById(R.id.imgViewBlue);
ImageView yellow = (ImageView)findViewById(R.id.imgViewYellow);
AlphaAnimation transparency = new AlphaAnimation(1, 0);
transparency.setDuration(500);
transparency.start();
green.startAnimation(transparency);
red.startAnimation(transparency);
blue.startAnimation(transparency);
yellow.startAnimation(transparency);
}
I'm not sure if this is the most elegant solution, but you could achieve this pretty easily with a handler that you can send messages to at 500ms intervals.
private int mLights = new ArrayList<ImageView>();
private int mCurrentLightIdx = 0;
private Handler mAnimationHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ImageView currentLightIdx = mLights.get(currentLight);
AlphaAnimation transparency = new AlphaAnimation(1, 0);
transparency.setDuration(500);
transparency.start();
currentLight.startAnimation(transparency);
currentLightIdx++;
if(currentLightIdx < mLights.size()){
this.sendMessageDelayed(new Message(), 500);
}
};
public void computerLights()
{
ImageView green = (ImageView)findViewById(R.id.imgViewGreen);
ImageView red = (ImageView)findViewById(R.id.imgViewRed);
ImageView blue = (ImageView)findViewById(R.id.imgViewBlue);
ImageView yellow = (ImageView)findViewById(R.id.imgViewYellow);
mLights.add(green);
mLights.add(red);
mLights.add(blue);
mLights.add(yellow);
mAnimationHandler.sendMessage(new Message());
}
After the first message is sent the handler will continue to send messages every 500ms until all of the animations have been started.

Categories

Resources