Thursday, November 4, 2021

jetpack compose - Pass onClick event to function

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedObjectState: Bundle?) {
        super.onCreate(savedObjectState)
        setContent {
            GetScaffold()
        }
    }


    @Composable
    fun GetScaffold() {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            text = "Compose - Pass onClick event to function"
                        )
                    },
                    backgroundColor = Color(0xFFB9966a),
                )
            },
            content = { MainContent() },
            backgroundColor = Color(0xFFfaf0e6)
        )
    }


    @Composable
    fun MainContent() {
        val counter = remember { mutableStateOf(0)}

        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(8.dp),
            modifier = Modifier
                .fillMaxSize()
                .padding(12.dp)
        ) {
            Text(
                text = "Counter " + counter.value,
                style = MaterialTheme.typography.h4,
                modifier = Modifier.padding(24.dp)
            )

            GetButton(text = "Add One", onClick = {counter.value++})

            GetButton(text = "Add Two") {
                counter.value +=2
            }

            GetButton(text = "Add Five") {
                counter.value +=5
            }

            GetButton(text = "Minus Three") {
                counter.value -=3
            }
        }
    }


    @Composable
    fun GetButton(
        text:String,
        onClick: ()-> Unit,
    ){
        Button(
            onClick = onClick,
            shape = RoundedCornerShape(8.dp)
        ){
            Text(
                text = text,
                Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
            )
        }
    }
}