Saturday, September 11, 2021

jetpack compose - Get context

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.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
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 - Get Context",
                    color = Color.White)},
                backgroundColor = Color(0xFF333399)) },
            content = { MainContent()}
        )
    }


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

        Box(
            Modifier.fillMaxSize().background(Color(0xFFEDEAE0)),
            contentAlignment = Alignment.Center,
        ){
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp)
            ) {

                Button(onClick = {
                    Toast.makeText(
                        context,
                        "I am a toast message",
                        Toast.LENGTH_SHORT
                    ).show()
                }) {
                    Text(text = "Show Toast")
                }

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


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


// extension function to show toast message
fun Context.showToastMessage(message:String){
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}