Latest News

Show Toast On Button Click Android Studio

In this tutorial we will learn how to use Toast in android. We will create a button when this button is clicked the toast will be displayed. Follow the following steps to display the toast..

Step 1:  Create a new project OR Open your project

Step 2: Code to display toast:

For Short Time(2 seconds):
Toast.makeText(MainActivity.this , "MESSAGE" , Toast.LENGTH_SHORT).show();

For Long Time(3.5seconds):
Toast.makeText(MainActivity.this , "This is Toast..." , Toast.LENGTH_LONG).show();

For Custom Time(e.g 6 seconds):
for (int i=0; i < 3; i++) {  Toast.makeText(MainActivity.this , "MESSAGE" , Toast.LENGTH_SHORT).show(); }

Step 3: To display Toast on Button click:

Step 3.1: activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/showtoastbtn"android:text="Show Toast"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>

Step 3.2: MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button showToastBtn = findViewById(R.id.showtoastbtn);showToastBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Toast.makeText(MainActivity.this , "This is Toast..." , Toast.LENGTH_LONG).show();}});}}

Step 4: Run the project

Output:

0 Response to "Show Toast On Button Click Android Studio"