Tuesday, March 2, 2021

jetpack compose - How to use Button

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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 {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        var counter = 0

        Button(
            onClick = {
                counter++
                  Toast.makeText(
                      this,
                      "Clicked $counter time(s).",
                      Toast.LENGTH_SHORT
                  ).show()
            },

            colors = ButtonDefaults.textButtonColors(
                backgroundColor = Color.Black,
                contentColor = Color.White
            ),

            modifier = Modifier.padding(15.dp)
        ) {
            Text(text = "Click Me")
        }
    }


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