Latest News

Android Custom Toast Example - Android Studio

In this tutorial we will learn how to display Custom Toast(with Image , Text) on a Button click using Android Studio. We will create a layout resource file for custom Toast.

Step 2: Place an image in drawable folder(if you want to display the image too)

Step 3: Create a Layout resource file named as custom_toast.xml in res>layout folder

Step 4: Code

custom_toast.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/custom_toast_layout"android:orientation="vertical"><ImageViewandroid:id="@+id/custom_toast_icon"android:layout_width="80dp"android:layout_height="80dp"android:src="@drawable/icon"/><TextViewandroid:id="@+id/custom_toast_msg"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="This is custom toast..." /></LinearLayout>

activity_main.xml
<LinearLayout 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:orientation="vertical"android:padding="10dp"tools:context=".MainActivity" > <Button android:id="@+id/btnShowCusToast" android:text="Show Custom Toast" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>

MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.Gravity;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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button mBtnShowCusToast = findViewById(R.id.btnShowCusToast);//Create the LayoutInflater instanceLayoutInflater layoutInflater = getLayoutInflater();//Get the View object as defined in the custom_toast.xml fileView layout = layoutInflater.inflate(R.layout.custom_toast ,(ViewGroup) findViewById(R.id.custom_toast_layout));//Create the Toast objectfinal Toast toast = new Toast(getApplicationContext());toast.setDuration(Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER_VERTICAL , 0 , 0);toast.setView(layout);//set the view of custom toast layout//handle button click to show toastmBtnShowCusToast.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//show toasttoast.show();}});}}

Step 5: Output

 

0 Response to "Android Custom Toast Example - Android Studio"