Android Jetpack Compose – Set onClick for Button

In this tutorial, we will learn how to execute a block of code when user clicks on a Button in Android Compose.

To execute a block of code when user clicks on a Button in Android Jetpack Compose, set onClick parameter with the block of statements.

Button(onClick = {
  //code
})

Example

In this example, we have UI with a Button. The button has the text Submit. For this button, we will set onClick parameter.

For onClick parameter, we write code to show Toast. So, when user clicks on the button, the Toast is displayed for specified duration of time.

Create a Project in Android Studio with empty compose activity template, and modify MainActivity.kt file as shown in the following.

MainActivity.kt

</>
Copy
package com.example.myapplication

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Column(modifier = Modifier.padding(20.dp)) {
                    val context = LocalContext.current
                    Button(onClick = {
                        Toast.makeText(context, "You clicked me!", Toast.LENGTH_SHORT).show()
                    }) {
                        Text("Submit")
                    }
                }
            }
        }
    }
}

Screenshot 1 – Application startup

Android Compose Button onClick

Screenshot 2 – After clicking on Submit button

Android Compose Button onClick

Conclusion

In this Android Jetpack Compose Tutorial, we learned how to set onClick parameter for Button in Android Jetpack Compose.