Toast

Toast in Android

In this tutorial we will explain how to deal with the Toast in Android with simple toast with example. 

Toast:

A toast provides a simple feedback about an operation in a small popup. It only fills the amount of space required for a message.

We can instantiate a android.widget.Toast object using static makeText() method. This method takes three parameters: the application Context, the text message, and the duration for the toast. You can display the toast notification by calling show() method.

//  Toast with long period of time      
Toast.makeText(getApplicationContext(),"Your Message Here",Toast.LENGTH_LONG).show();

//  Toast with short period of time     
 Toast.makeText(getApplicationContext(),"Your Message Here",Toast.LENGTH_SHORT).show();

Example:


  • Now create a new project in Android Studio, We will show a Toast on Click of a Button in example.
File: activity_main.xml:

<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:paddingBottom="@dimen/activity_vertical_margin"    
android:paddingLeft="@dimen/activity_horizontal_margin"    
android:paddingRight="@dimen/activity_horizontal_margin"    
android:paddingTop="@dimen/activity_vertical_margin"    
tools:context="com.example.hss_24.toast.MainActivity">

   <Button       
android:id="@+id/button"       
android:layout_width="match_parent"       
android:layout_height="wrap_content"       
android:text="Click Me "       
android:layout_alignParentTop="true"       
android:layout_alignParentRight="true"       
android:layout_alignParentEnd="true"       
android:layout_marginTop="158dp" />

</RelativeLayout>


File: MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override            
              public void onClick(View v) {
       Toast.makeText(getApplicationContext(), "You Clicked A Button", Toast.LENGTH_LONG).show();
            }
        });

    }
}                                                                                                    












































Thank you!!!!
Please like and share...

Comments