An example of Simple Toast in Android

In this article, we will learn about simple toast in Android. How to set toast on click and to set its length to display?
Submitted by Shamikh Faraz, on January 21, 2018

Toast is simply a notification that pops up. It is shown for a certain amount of time, and automatically fades in and out. You just set its display timer either ‘short’ or ‘long’. But you can’t set time duration in ‘short’ and ‘long’.

XML File: (activity_main)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.faraz.simpletoast_example.MainActivity">

    <Button
        android:id="@+id/buttonToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Toast" />
</android.support.constraint.ConstraintLayout>

JAVA File: (MainActivity.java)

package com.example.faraz.customtoast_example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button btn;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.buttonToast);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast.makeText(getApplicationContext(),"This is an Android Toast Message", Toast.LENGTH_SHORT).show();

            }
        });
    }
}

Output

Android - Simple Toast Example

Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.