Wednesday, 8 August 2012

Splash Screen

Splash Screen : 
           We can observe sometimes when we start any application we find an image which will be shown for few seconds before the actual content of the application is shown. This is a splash screen.
Lets start a sample code where we discuss showing a splash screen.

Design an xml file named splash.xml as below.



  • <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:background="@drawable/splash_screen" >
  • </RelativeLayout>
Here splash_screen is an image that i want to set as a splash.
Now let us code the activity file where the splash stays for 5 sec and is redirected to the main actual content of the app.
             
Write the following code in the onCreate() of the activity.

  • public void onCreate(Bundle savedInstanceState) {
  •         super.onCreate(savedInstanceState);
  •         setContentView(R.layout.splash);
  •         Thread splash = new Thread() {
  •             @Override
  •             public void run() {
  •                 try {
  •                        sleep(5000);
  •                     
  •                 } catch(InterruptedException e) {
  •                     // do nothing
  •                 } 
    •           finish();
  •                     Intent i = new Intent(SplashActivity.this,FirstActivity.class);
  •                     startActivity(i);
  •                     stop();
  •    
    •  }
  •         };
  •         splash.start();
  •     
    }

Here SplashActivity is my class name and the FirstActivity is the activity to which i am redirecting to. Just i am using a thread and using sleep() method so that the particular activity will be in a sleep state for 5 seconds.
Later  am finishing the activity and starting the new activity FirstActivity and stopping the thread.
splash.start() calls the thread which runs the run() and performs all the above process(sleeping for 5 seconds and displaying the next activity).

In the FirstActivity class i just displayed a TextView. 

here are the splash screen and the next activity ...




That's it. The splash 

Any suggestions are welcomed.
Please comment if anyone has some or the other problem with this one.







              

No comments:

Post a Comment