How to create a blinking text in Android?

By | September 13, 2012

Hello everyone…

Here I am explaining two methods on how to create a blinking textview in Android.

One with the help of Animation class and other with a Logic.

Now let’s see that..

Place a textview with an id of “tv” in your layout and attempt this.

package com.coderzheaven.blinktext;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blinkText();
        //blinkText2();
    }
    
    private void blinkText(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
            int timeToBlink = 1000;    //in ms
            try{
            	Thread.sleep(timeToBlink);
        	}catch (Exception e) {
        		
        	}
            handler.post(new Runnable() {
                @Override
                    public void run() {
                    TextView txt = (TextView) findViewById(R.id.tv);
                    if(txt.getVisibility() == View.VISIBLE){
                        txt.setVisibility(View.INVISIBLE);
                    }else{
                        txt.setVisibility(View.VISIBLE);
                    }
                    blinkText();
                }
                });
            }}).start();
   }
    
    public void blinkText2(){
    	TextView myText = (TextView) findViewById(R.id.tv );

    	Animation anim = new AlphaAnimation(0.0f, 1.0f);
    	anim.setDuration(50); //You can manage the time of the blink with this parameter
    	anim.setStartOffset(20);
    	anim.setRepeatMode(Animation.REVERSE);
    	anim.setRepeatCount(Animation.INFINITE);
    	myText.startAnimation(anim);
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    
}

Download the complete android source code from below.

Download.

Website Pin Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google StumbleUpon Premium Responsive

Leave a Reply

Your email address will not be published. Required fields are marked *