Sunday 17 May 2015

Blinking text animation in Android

Background

In last post we saw how to do a simple animation of bouncing ball. In this we will see how to make a text blink using ObjectAnimator. We will make text - "Hello World!" start and stop blinking using buttons.

Creating the Layout

 Create layout file - blinking_text_layout.xml and add following content in it.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/startBlinkTextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Start Blinking Text" />

    <Button
        android:id="@+id/stopBlinkTextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/startBlinkTextButton"
        android:layout_centerHorizontal="true"
        android:text="Stop Blinking Text" />

    <TextView
        android:id="@+id/blinkTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/stopBlinkTextButton"
        android:layout_centerHorizontal="true"
        android:paddingTop="10dp"
        android:text="Hello World!"
        android:textSize="40sp" />

</RelativeLayout>

The layout should get rendered on your phone as follows -



Now lets write code to animate this text.

Animate Blinking of Text

As you can see from the layout we have two buttons - one to start the blinking animation and other to stop it. Code is as follows - 


package com.osfg.animationdemo;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AnimationStarter extends Activity {

    private static final String TAG = "AnimationStarter";
    ObjectAnimator textColorAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blinking_text_layout);

        Button startBlinkTextButton = (Button) findViewById(R.id.startBlinkTextButton);
        Button stopBlinkTextButton = (Button) findViewById(R.id.stopBlinkTextButton);
        final TextView blinkText = (TextView) findViewById(R.id.blinkTextView);

        startBlinkTextButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                textColorAnim = ObjectAnimator.ofInt(blinkText, "textColor", Color.BLACK, Color.TRANSPARENT); 
                textColorAnim.setDuration(1000); 
                textColorAnim.setEvaluator(new ArgbEvaluator());     
                textColorAnim.setRepeatCount(ValueAnimator.INFINITE); 
                textColorAnim.setRepeatMode(ValueAnimator.REVERSE); 
                textColorAnim.start();
            }
        });
        
        stopBlinkTextButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(textColorAnim != null) {
                    textColorAnim.cancel();
                    blinkText.setTextColor(Color.BLACK);
                }
            }
        });

    }

}


Notice on "Stop Blinking Text" button press we are simply cancelling the current animation and setting the color back to black as the transparency of the text can be different as per the state in which the blinking animation was cancelled.

Note :
  • clearAnimation() method of View will have no effect on ObjectAnimator.
  • If you call start() on your ObjectAnimator instance n times then you will have to call cancel() n times for animation to completely stop.

 You can try out the code. Recorded video is as follows - 



Related Links

Creating bouncing ball Animation in Android

Background

In this post I am going to show a very simple animation - Bouncing a ball. As much as Animations are very cool to look at, they are tricky and must be handled carefully.

Animation coding Tip : Just a tip here. Animations are generally started in onResume() method and stopped in onPause() method. You should not do it in onCreate() and onDestroy() methods as these methods are not guaranteed to be invoked every time.


Creating the Layouts

Lets create layouts that we will need to create a animated bouncing ball. To start with lets first create our ball.

For this I am going to create an oval shape in android. This will be in ball_shape.xml file under drawable folder. Contents of it are - 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#8c0000" />

    <stroke
        android:width="2dp"
        android:color="#fff" />
    
    <size
        android:height="80dp"
        android:width="80dp" />

</shape>

This is a simple circular shape with red color fill. We will use this as our ball. Now lets go ahead and create our actual layout with a button to animate this ball and of course the ball itself.

Put following content inside animation_layout.xml file under layout folder.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/bounceBallButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Bounce Ball" />

    <ImageView
        android:id="@+id/bounceBallImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/bounceBallButton"
        android:background="@drawable/ball_shape" />

</RelativeLayout>


As you can see we have a button and a ball (essentially ImageView with background set as oval shape) below it. Let's animate this now with our code. Layout will looks as follows -



Animating Bouncing Ball

To animate the ball we fill first set the layout of the Activity with the layout xml we have just created. Then we will get reference to our Button and ball and when user click on the button we will animate the ball so that it appears like bouncing.

Here is the code for it.

package com.osfg.animationdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageView;

public class AnimationStarter extends Activity {

    private static final String TAG = "AnimationStarter";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_layout);

        Button bounceBallButton = (Button) findViewById(R.id.bounceBallButton);
        final ImageView bounceBallImage = (ImageView) findViewById(R.id.bounceBallImage);

        bounceBallButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                bounceBallImage.clearAnimation();
                TranslateAnimation transAnim = new TranslateAnimation(0, 0, 0,
                        getDisplayHeight()/2);
                transAnim.setStartOffset(500);
                transAnim.setDuration(3000);
                transAnim.setFillAfter(true);
                transAnim.setInterpolator(new BounceInterpolator());
                transAnim.setAnimationListener(new AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                        Log.i(TAG, "Starting button dropdown animation");

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        Log.i(TAG,
                                "Ending button dropdown animation. Clearing animation and setting layout");
                        bounceBallImage.clearAnimation();
                        final int left = bounceBallImage.getLeft();
                        final int top = bounceBallImage.getTop();
                        final int right = bounceBallImage.getRight();
                        final int bottom = bounceBallImage.getBottom();
                        bounceBallImage.layout(left, top, right, bottom);

                    }
                });
                bounceBallImage.startAnimation(transAnim);
            }
        });

    }

    private int getDisplayHeight() {
        return this.getResources().getDisplayMetrics().heightPixels;
    }
}


We have simply used Translate Animation with bounce interpolator so that our ball can be viewed as bouncing vertically .You can install and try out this code. You can see the recorded video below -






Related Links


Centering a button in android Linear and Relative Layouts

Background

I have tried centering various views in Android and each time I end by with incorrect layouts. So in this post I am going to cover how to center a simple button in your layout. I will show this for both layouts -
  1. Linear Layout and
  2. Relative Layout
Before we proceed to see how the actual layout files look like lets see the two layout view attributes that are commonly confused with -
  1. android:gravity and : Sets the gravity of the content of the View it's used on.
  2. android:layout_gravity  : Sets the gravity of the View or Layout relative to its parent.
So generally you can either put android:gravity="center" on the parent or android:layout_gravity="center" on the child.

Centering a Button in Linear Layout

For Linear layout you should use xml (button_linear.xml) that looks something like below - 


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/centerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>


This will place the button on the center of the screen. If you want to center it just vertically or horizontally you can use following values in  android:gravity tag - 
  • center_vertical|center_horizontal or center (For centering in whole screen)
  • center_vertical (For centering vertically)
  • center_horizontal (For centering horizontally)
and layout should look like



 Now let's see the same in a Relative layout.

Centering a Button in Relative Layout

In Relative Layout the xml would be

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/centerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World!" />

</RelativeLayout>

Notice the  android:layout_centerInParent attribute

This will put the button in the center of entire screen. Analogous to linear layout , attributes that can be used here are - 
  1. android:layout_centerInParent="true" (For centering in whole screen)
  2. android:layout_centerVertical="true" (For centering vertically)
  3. android:layout_centerHorizontal="true" (For centering vertically)
 Layouts will look same as the screenshots provided above for linear layout.

Related Links

t> UA-39527780-1 back to top