Saturday, 21 July 2012

Android Toast Tutorial


Introduction of Android Toast Control



Situation : Everyone uses javascript alert() function. This function display a message to user. Same functionality in android achieved by Toast.
Android use toast control for messaging(notification) purpose. Using this we can show any message to user. Android provides a limited time period for toast after that it becomes invisible.

Android provides Toast class. This class has makeText() method. this method set message which we want to display. After this we use show() method to display a message to users.
 Syntex :
 
 
 Toast.makeText(ApplicationContext,message,Time to display).show();
 
 
makeText() method 

This method needs following parameters
  1. First we need to set current ApplicationContext. We can get current application context usingthis.getApplicationContext property.
  2. Then as second parameter we need to set message. User can set desired message.
  3. Then we need to set time period to display. For this purpose android provides inbuilt timer.
    • Toast.LENGTH_LONG : this set message for long time duration.
    • Toast.LENGTH_SHORT : this set message for short time duration.
show() method

this method is helpful for showing message to user.
Example
  1. Make layout file which contains a button. If we click on button it show notification toast message.

    <?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:orientation="vertical" >
    
       
    
    
        <Button
    
            android:id="@+id/buttonToast"
    
            android:layout_width="wrap_content"
    
            android:layout_height="wrap_content"
    
            android:text="Toast Message" />
    
    </LinearLayout>
    
  2. Then apply onclick event in mainactivity.class

    public class MainActivity extends Activity {
     
    	private Button button;
     
    	public void onCreate(Bundle savedInstanceState) {
     
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
     
    		button = (Button) findViewById(R.id.buttonToast);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			  @Override
    			  public void onClick(View arg0) {
     
    			     Toast.makeText(getApplicationContext(), 
                                   "Button is clicked", Toast.LENGTH_LONG).show();
     
    			  }
    		});
    	}
    }
    
    
  3. Output : 
                    
      

No comments:

Post a Comment