Custom Toast in Android using Kotlin
In previous article we have discussed on what is Toast and its syntax check out on this link if required What is toast and basic example of toast using kotlin Toast Example this will be continued article of previous
activity_main.xml
Add the below code in your activity_main.xml file , this file contains button which on click will display the toast
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"> <Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Toast Example"/>
</LinearLayout>
custom_toast.xml
Create custom_toast.xml layout file and design the toast as per your requirement in this example we have created an imageview and textview where textview displays the message and imageview displays the image given in source
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/linear"android:orientation="vertical"> <ImageViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/toast_img"android:src="@drawable/logo"/><TextView android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/toast_txt"android:text="Welcome to SDK Book"/></LinearLayout>
MainActivity.kt
Add below code in MainActivity.kt class, in this class we are inflating the custom_toast.xml layout created and on button click the toast message will be displayed as in custom_toast
package com.example.kotlinsampleproject import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.widget.LinearLayout import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.custom_toast.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Inflating toast custom layoutval custom_layout= layoutInflater.inflate(R.layout.custom_toast,linear); //on button click displaying custom toastbutton.setOnClickListener {val mytoast=Toast(this) mytoast.duration=Toast.LENGTH_LONGmytoast.view = custom_layout mytoast.show(); } } }Happy Reading 😊Thank YouSushmitha NHi there ! Im a experienced android developer with 4years of revelant exprience.My Skills include Android,Core Java ,Oops and Kotlin.Youtube Channel : SDK Book
Comments
Post a Comment