Saturday, September 11, 2021

jetpack compose - Show toast message

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold(){
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(
                    "Compose - Toast Message",
                    color = Color.White)},
                backgroundColor = Color(0xFF2A52BE)) },
            content = { MainContent()}
        )
    }


    @Composable
    fun MainContent(){
        val context = LocalContext.current

        Row(
            Modifier.fillMaxSize().padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ){
            Button(onClick = {
                Toast.makeText(
                    context,
                    "I am a toast message",
                    Toast.LENGTH_SHORT
                ).show()
            }) {
                Text(text = "Show Toast")
            }

            Button(onClick = {
                showToastMessage(context,"Another toast message")
            }) {
                Text(text = "Show Another Toast")
            }
        }
    }


    private fun showToastMessage(context: Context, message:String){
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}