Blog purpose for android basic example for android app developer. any query please my contact

Thursday, 16 February 2023

kotlin toast example

 kotlin toast example


In the code above, we first obtain the context of the application. This is necessary because a Toast message needs to be displayed within the context of an Activity or Service.


val context = applicationContext

val message = "Hello, world!"

val duration = Toast.LENGTH_SHORT


val toast = Toast.makeText(context, message, duration)

toast.show()


Full Example kotlin toast 


activity_main.xml:


<?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.tutorialkart.myapplication.ToastActivity">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:gravity="center"

        android:padding="25dp"

        android:orientation="horizontal">

        <Button

            android:id="@+id/btn_click_me"

            android:background="@drawable/btn_round_edge"

            android:text="Click me for Toast"

            android:textAllCaps="false"

            android:padding="10dp"

            android:textSize="25dp"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>



2.MainActivity.Kt:


import android.support.v7.app.AppCompatActivity

import android.os.Bundle

import android.widget.Button

import android.widget.Toast

 

class MainActivity : AppCompatActivity() {

 

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_toast)

 

        var btn_click_me = findViewById(R.id.btn_click_me) as Button

 

        btn_click_me.setOnClickListener {

            // make a toast on button click event

            Toast.makeText(this, "Hi there! This is a Toast.", Toast.LENGTH_LONG).show()

        }

    }

}

No comments:

Post a Comment