Android Custom Toast example

Android Toast is used to display message for short span of time. Message appears on the screen for short span of time then disappears after some time.

We have already used toast in previous examples like Android SeekBar , Android RatingBar .
In this post, I am going to demonstrate how to make custom toast and use in your app.

Source code:

Lets create Android custom toast example:

Step 1 : Creating Project

Create an android application project named “CustomToastExampleApp”.

Step 2: Put any image in drawable folder with name “custom_toast_image”

Step 3 : Creating custom toast layout file

  • Go to res -> layout
  • Right click on layout
  • Click on New -> File.
  • Create a file named “custom_toast.xml” and paste below code in custom_toast.xml.


 

 

Step 4 : Creating Layout

Change res ->layout -> activity_main.xml as below:




 

Step 5 : Creating MainActivity

Change src/main/packageName/MainActivity.java as below:

package com.java2blog.splashscreenexampleapp;

import android.app.Activity;
import android.os.Bundle;
package com.java2blog.customtoastexampleapp;

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

public class MainActivity extends AppCompatActivity {

    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                //Creating the LayoutInflater instance
                LayoutInflater liCustomToast = getLayoutInflater();
                //Getting the View object as defined in the custom_toast.xml file
                View layout = liCustomToast.inflate(R.layout.custom_toast,
                        (ViewGroup) findViewById(R.id.custom_toast_layout));

                //Creating the Toast object
                Toast toast = new Toast(getApplicationContext());
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);//setting the view of custom toast layout
                toast.show();

            } });
    }
}

It is default MainActivity provided by HelloWorld app.

Step 6 : Running the app

When you run the app, you will get below screen:

When you click on the button, you will get below screen.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.