jetpack compose - LazyColumn add remove item

Compose LazyColumn Add Remove Item
The LazyColumn is an equivalent widget of RecyclerView. But there is no adapter for LazyColumn. Like RecyclerView, LazyColumn does not need any adapter to populate items. In this case, we can show items in a LazyColumn widget using a simple list. Yes, we talked about the jetpack compose library LazyColumn widget.

LazyColumn shows a vertically scrollable list of items. This is super fast and took a much smaller memory size. The items are composed when they are in a visible state in a LazyColumn. As with adding a list to the LazyColumn items collection we can even add a single item to the LazyColumn.

The following android jetpack compose tutorial code will describe to us how we can add and remove an item from LayColumn. To do this, we create a mutable list of string values which we generate from a random UUID. We also remember the items of the mutable list using the jetpack compose library API. To generate LazyColumn items we used its LazyListScope.itemsIndexed() inline function and pass the mutable list as its argument. So our LazyColumn now shows items on it and they have an index associated with it.

This index number helps us to identify the LazyCoumn specified item from the mutable list. We know we can add and remove an item from a mutable list. Those are the important properties of a mutable list. So when we add an item to the mutable list, its ‘remember’ feature also updates the LazyColumn and shows the newly added item to its items collection. The same thing happened when we remove an item from the mutable list, the LazyColumn instantly remove/delete the associated item from its list.

In this kotlin tutorial, we put a remove button inside each item of LazyColumn. So, when an app user click’s the remove button it removes the associated item from the mutable list and LazyColumn also updates its internal list. We can properly identify the LazyColumn associated mutable list item using its index number. Jetpack compose library AnimatedVisibility animates the visibility of the LazyColumn items.

Copy the code directly from here and paste it into your android studio IDE main activity file. Compile the code and run the generated apk to an emulator device, so you can test the LazyColumn item’s add and remove functionality in your hand. The following screenshots help you to understand the LazyColumn add and remove techniques without writing the code in your android studio IDE.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.util.*

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

        setContent {
            MainContent()
        }
    }


    @ExperimentalAnimationApi
    @Composable
    fun MainContent(){
        Box(
            Modifier

                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(8.dp)
        ) {
            val uuids = remember { mutableStateListOf<String>() }

            LazyColumn(
                Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                itemsIndexed(uuids) { index, item ->
                    val visibility by remember {
                        mutableStateOf(
                            uuids.contains(item) && item == uuids[index]
                        )
                    }

                    AnimatedVisibility(
                        visible = visibility
                    ) {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight(
                                    align = Alignment.CenterVertically
                                ),
                            elevation = 4.dp,
                            shape = RoundedCornerShape(8.dp),
                            backgroundColor = if (index % 2 == 0)
                                Color(0xFF8DB600) else
                                    Color(0xFF48BF91)
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(12.dp),
                                horizontalAlignment =
                                    Alignment.CenterHorizontally,
                                verticalArrangement =
                                    Arrangement.spacedBy(8.dp)
                            ) {
                                Text(
                                    text = item.take(5).capitalize(),
                                    modifier = Modifier.padding(
                                        start = 12.dp, top = 12.dp,
                                        end = 12.dp, bottom = 4.dp
                                    ),
                                    textAlign = TextAlign.Center,
                                    fontSize = 30.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color.White
                                )
                                TextButton(
                                    onClick = { uuids.removeAt(index) },
                                    colors = ButtonDefaults.textButtonColors(
                                        backgroundColor = Color(0xFF960018),
                                        contentColor = Color.White
                                    )
                                ) {
                                    Text(text = "Remove")
                                }
                            }
                        }
                    }

                }
            }

            FloatingActionButton(
                onClick = {
                    UUID.randomUUID().toString().apply {
                        uuids.add(this)
                    }
                },
                Modifier.align(Alignment.BottomEnd),
                backgroundColor = Color(0xFFFE4164)
            ) { Icon(Icons.Filled.Add,"") }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - LazyColumn items indexed

Compose LazyColumn Items Indexed
The LazyColumn is a special type of Column layout that has items vertical scrolling feature enabled. In the pre-compose application, there is a similar widget name RecyclerView. Like the RecyclerView widget, LayColumn is used to display a long list of items.

Items may come from a room database, API data, or whatever it is. The main feature of the LazyColumn widget is, that it shows a vertically scrolling list that only composes and lays out the currently visible items. This feature allows a LazyColumn to scroll a long list very smoothly and it also takes a small size of device memory.

We can add a single item to the LazyColumn items collection, we also can add multiple items to its items collection at once. But how does an android jetpack compose developers add items to the LazyColumn collection of items with their index value? This jetpack compose tutorial will describe to us how we can get LazyColumn items with their corresponding index value.

The LazyColumn’s ‘LazyListScope.itemsIndexed()’ inline function allows us to pass an items list to the LazyColumn items collection. This inline function also allows us to access two variables while iterating its items, the first one is the item’s index value and the second one is the item itself. So, we can easily display the item’s associated index value to the app user interface and we also can use this index value to perform other related actions.

In this jetpack compose tutorial we display a list of items with the item counter. We generate the counter by adding one with the item index value because the index is zero-based.

The following kotlin code is written in an android studio IDE. Copy the code and paste it into your android studio compose project main activity file and run the app on an emulator to see the result. At the bottom of this tutorial we also displayed screenshots of this code output, this also can help you to understand the terms without running it on an android device.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Box(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(8.dp)
        ) {
            val alphabets = listOf("A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")

            LazyColumn(
                Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                itemsIndexed(alphabets){ index, item ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight(
                                align = Alignment.CenterVertically
                            ),
                        elevation = 4.dp,
                        shape = RoundedCornerShape(8.dp),
                        backgroundColor = Color(0xFF7BB661)
                    ) {
                        Text(
                            text = "${index+1}. " + item,
                            modifier = Modifier.padding(25.dp),
                            textAlign = TextAlign.Center,
                            fontSize = 35.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - Card click

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.shape.RoundedCornerShape
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.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var counter by  remember { mutableStateOf(0) }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(align = Alignment.CenterVertically)
                    .clickable {
                        counter++
                    },
                elevation = 4.dp,
                shape = RoundedCornerShape(8.dp),
                backgroundColor = Color(0xFF568203)
            ) {
                Text(
                    text = "Counter : $counter",
                    modifier = Modifier.padding(35.dp),
                    textAlign = TextAlign.Center,
                    fontSize = 35.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(align = Alignment.CenterVertically)
                    .pointerInput(Unit) {
                        detectTapGestures(
                            onTap = {
                                counter--
                            }
                        )
                    },
                elevation = 4.dp,
                shape = RoundedCornerShape(8.dp),
                backgroundColor = Color(0xFFD3212D)
            ) {
                Text(
                    text = "Counter : $counter",
                    modifier = Modifier.padding(35.dp),
                    textAlign = TextAlign.Center,
                    fontSize = 35.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField IME action done

Compose TextField IME Action Done
TextField is an equivalent widget of the android view system’s EditText widget. In a jetpack compose application TextField is used to enter and modify text. So, TextField is a Text input widget of the jetpack compose library.

The following jetpack compose tutorial will demonstrate to us how can we show IME action ‘Done’ on the soft keyboard and how we can respond to IME action Done click.

TextField constructor’s ‘keyboardOptions’ argument allows us to set the TextField-related soft keyboard’s IME action. We can set one of the options from Default, Done, Sent, Go, Next, Search, etc. The ‘ImeAction.Default’ is the default value for this argument. So using this keyboardOptions parameter we set the IME action Done. IME action Done represents that the user is done providing input to a group of inputs.

On the other hand, TextField ‘keyboardActions’ argument allows us to specify actions that will be triggered in response to users triggering IME action on the software keyboard. So, we can handle the IME action done event in this ‘keyboardActions’ parameter’s ‘onDone’ section.

In this tutorial, we clear the focus from the TextField widget on the IME action done event. We also show a message that the IME action ‘Done’ triggers with user inputted text.

Copy the following code snippet into your android studio IDE. Run the code on an emulator device to check how we implemented the TextField IME action ‘Done’. The screenshots also help you to understand the scenario without running it into a device.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            var txt by remember { mutableStateOf("") }

            val localFocusManager = LocalFocusManager.current

            Text(
                text = txt,
                fontSize = 22.sp,
                fontFamily = FontFamily.Monospace,
                color = Color(0xFF0047AB)
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Input your name") },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Done
                ),
                keyboardActions = KeyboardActions(
                    onDone = {
                        localFocusManager.clearFocus()
                        txt = "IME action done : " + textState.text
                    }
                )
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField focus change listener

Compose TextField Focus Change Listener
TextFIeld is a widget of the android jetpack compose library. This widget is used for entering text and modifying text on an app screen. Android view system’s EditText is an equivalent of the jetpack compose TextField widget. TextField widget has a very easy API to request focus on it, remove focus from it and handle the focus change listener.

The ‘FocusRequester’ object is used in conjunction with ‘Modifier.focusRequester’ to send requests to change focus. So, we can use this Modifier object’s ‘focusRequester’ element to set the focus on a TextField widget programmatically.

FocusManager.clearFocus() method clear focus from the currently focused component and set the focus to the root focus modifier. So we can remove focus from a TextField using FocusManager.clearFocus() method. We have to create an instance of LocalFocusManager and call its clearFoucs() method to remove focus from TextField.

So, we can request focus for a TextField widget and also can remove focus from a TextField widget, then how we can handle the TextField focus change listener? Ok, this android jetpack compose tutorial will demonstrate to us how we can handle the TextField focus change listener.

Modifier object’s ‘onFocusChanged’ element observes focus state event. The Modifier.onFocusChanged is invoked when the specified widget’s focus state changes. So we can use the TextField widget modifier object’s ‘onFocusChanged’ element to handle or listen to the TextField focus change event.

In this tutorial, we show a message to the app interface while TextField’s focus change. When TextField gets focus we show a message and when TextField loses focus we display another message to the app user.

This tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE main activity file and run it on an emulator device to test how we handle the TextField widget’s focus change listener. Screenshots are also displayed at the bottom of the code snippets. Look at those to understand the code entirely.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            var focusState by remember { mutableStateOf("") }

            val localFocusManager = LocalFocusManager.current
            val focusRequester = FocusRequester()

            Text(
                text = focusState,
                fontSize = 22.sp,
                fontFamily = FontFamily.Monospace,
                color = Color(0xFF0047AB)
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Input your name") },
                modifier = Modifier
                    .focusRequester(focusRequester)
                    .fillMaxWidth()
                    .onFocusChanged {
                        focusState = if (it.isFocused) {
                            "TextField is focused."
                        } else {
                            "TextField has no focus."
                        }
                    },
            )

            Button(onClick = {
                focusRequester.requestFocus()
            }) {
                Text(text = "Request Focus")
            }

            Button(onClick = {
                localFocusManager.clearFocus()
            }) {
                Text(text = "Clear Focus")
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField clear focus

Compose TextField Clear Focus
TextField is one of the most used widgets of the android jetpack compose library. A TextField is used for writing some text on the android user interface or modifying text in an app. TextField is the equivalent of the android view system’s EditText widget. They act likely the same in an android app. But the jetpack compose library provides us a different API to manage the TextField behaviors such as requesting focus on TextField and clear focus from a TextField widget.

This android jetpack compose tutorial will demonstrate how we can clear focus from a TextField widget programmatically. We can use FocusManager.clearFocus() method to clear focus from the currently focused component and set the focus to the root focus modifier. To do that we create an instance of LocalFocusManager and call its clearFocus() method to remove focus from TextField.

Finally, we used two Button widgets to make our tutorial. On the first Button click event, we set focus to our TextField widget. And on the second Button’s click event we clear/remove focus from the TextField widget programmatically. Here we call FocusRequester object’s requestFocus() method by a Button click event to request TextField focus programmatically. And call the FocusManager.clearFocus() method to clear focus from the TextField widget. So, we can say that FocusRequester.requestFocus() method allows us to set focus on its associated TextField and FocusManager.clearFocus() method remove focus from the currently focused component.

When we request or set focus on a TextField widget, the soft keyboard is visible on the app screen. On the other side when we clear or remove focus from a TextField widget then the soft keyboard hides/collapsed from the app screen. TextField also visually behaves differently on its focus state and unfocused state.

This tutorial code is written in an android studio IDE, so you can copy the code and paste it into your android studio IDE main activity file to check how we set focus on a TextField widget and how we also clear focus from TextField programmatically. Build apk and run it on an emulator device or on a physical android device to test it. Screenshots are also displayed at the bottom of the code snippets. Look at those to understand the code perfectly.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            val localFocusManager = LocalFocusManager.current
            val focusRequester = FocusRequester()

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Input your name") },
                modifier = Modifier
                    .focusRequester(focusRequester)
                    .fillMaxWidth(),
            )

            Button(onClick = {
                focusRequester.requestFocus()
            }) {
                Text(text = "Request Focus")
            }

            Button(onClick = {
                localFocusManager.clearFocus()
            }) {
                Text(text = "Clear Focus")
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField input type

Compose TextField Input Type
TextField is an equivalent widget of the android view system’s EditText widget. Jetpack compose TextField allows users to enter and modify text. That’s why TextField is a Text input widget of the jetpack compose library.

The following jetpack compose tutorial will demonstrate to us how we can input different types of text on the TextField widget using different types of Software keyboards. Such as how we can enter email, phone number, simple text, password, decimal, number, URI, etc to TextField with the specified soft keyboard type.

The TextField constructor’s ‘keyboardOptions’ parameter’s ‘keyboardType’ property allows us to define the Keyboard type for the focused TextField. The ‘keyboardType’ element accepts one value from Ascii, Decimal, Email, Number, NumberPassword, Password, Phone, Text, and Uri.

Those keyboard types are used for different purposes such as the ‘Decimal’ type soft keyboard used to request an IME that is capable of inputting decimals. The ‘Email’ type keyboard is used for inputting email addresses. The ‘Number’ type soft keyboard is used for inputting digits.

The ‘Password’ type keyboard is used for entering passwords. The ‘Uri’ type keyboard is used for entering URIs. And finally, the ‘Text’ type soft keyboard is used for displaying a regular keyboard and this ‘Text’ type keyboard is the default value for the ‘keyboardType’ element.

The following tutorial code placed some TextField widgets on the app screen. TextFields displays different types of keyboards in a focused state. Such as we displayed a regular Text type keyboard for a TextField, and a ‘Password’ type keyboard for another TextField. We also displayed an ‘Email’ type keyboard and a ‘Number’ type keyboard for separate TextFields.

Copy the code and run it into your android studio IDE to practically test how we displayed different types of soft keyboards for different TextField widgets. At the bottom of the code, we displayed screenshots of this tutorial's emulator output screen.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Keyboard Type Text") },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Text
                )
            )

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Keyboard Type Password") },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Password
                ),
                visualTransformation = PasswordVisualTransformation()
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Keyboard Type Email") },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Email
                )
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Keyboard Type Number") },
                modifier = Modifier.fillMaxWidth(),
                keyboardOptions = KeyboardOptions(
                    // more types are Ascii, NumberPassword, Phone, Uri
                    keyboardType = KeyboardType.Number
                )
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField error

Compose TextField Error
TextField is an equivalent widget of the android view system’s EditText widget. Jetpack compose TextField is used to enter and modify text. So, TextField is called a Text input widget of the jetpack compose library.

The following jetpack compose tutorial will demonstrate to us how we can handle errors on TextField. For example, how we can catch TextField error while users enter text on it, how we can show an error message on the TextField while an error occurred and how we can show different colors on the TextField widget to indicate that TextField generates an error.

The first question is, how we can catch an error from TextField while the user enters Text on it? The answer is TextField constructor’s ‘onValueChange’ argument allows us to catch errors in real-time while users enter text on It. We also can catch errors on TextField’s focused change.

We can make a TextField mandatory to input some text in it, if the user leaves the TextField blank then we can show an error message on the TextField immediately. Another example is if we ask for users to submit their age on a TextField and users enter text instead numbers on it then we can display an error message to the user.

We can display the error message inside the TextField itself such as on the label or the placeholder object. An android developer also can display TextField error messages outside of the TextField such as on a Text widget.

Let us explain the following tutorial code, at the top of the code, we initialize a variable to remember TextField’s error state. When TextField caused an error we set the value to true and when TextField has no error then we set its value to false. In this way, we can remember the specified TextField’s error state.

TextField constructor’s ‘isError’ argument allows us to mark whether a TextField is in an error state or not. If it is in an error state then the TextField shows different colors on it to notify users such as red color border. And its valid state TextField displays regular colors on it. Jetpack compose developers can customize the TextField error states color using its constructor’s ‘colors’ argument. Android developers can show an error message when TextField is in an error state.

This jetpack compose tutorial is written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we handle errors for a specified TextField. We also displayed screenshots of this tutorial’s emulator output screen.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            var errorState by remember { mutableStateOf(false)}
            var errorMessage by remember { mutableStateOf("")}

            var textState2 by remember { mutableStateOf(TextFieldValue()) }
            var errorState2 by remember { mutableStateOf(false)}
            var errorMessage2 by remember { mutableStateOf("")}

            TextField(
                value = textState,
                onValueChange = {
                    textState = it
                    when {
                        textState.text.isEmpty() -> {
                            errorState = true
                            errorMessage = "Name should not blank"
                        }
                        textState.text.startsWith("0") -> {
                            errorState = true
                            errorMessage = "Name should not start with zero"
                        }
                        else -> {
                            errorState = false
                            errorMessage = ""
                        }
                    }
                },
                label = {
                    Text(
                        text = if (errorState) errorMessage
                        else "Put your name here"
                    )
                },
                modifier = Modifier.fillMaxWidth(),
                isError = errorState
            )

            OutlinedTextField(
                value = textState2,
                onValueChange = {
                    textState2= it
                    when {
                        textState2.text.isEmpty() -> {
                            errorState2 = true
                            errorMessage2 = "City should not blank"
                        }
                        textState2.text.startsWith("0") -> {
                            errorState2 = true
                            errorMessage2 = "City should not start with zero"
                        }
                        else -> {
                            errorState2 = false
                            errorMessage2 = ""
                        }
                    }
                },
                label = {
                    Text(
                        text = if (errorState2) errorMessage2
                        else "Put your city here"
                    )
                },
                modifier = Modifier.fillMaxWidth(),
                isError = errorState2,
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    errorBorderColor = Color(0xFFE30022),
                    errorLabelColor = Color(0xFFFF0800),
                    errorCursorColor = Color(0xFF960018)
                )
            )
        }
    }



    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField size

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
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.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            var textState2 by remember { mutableStateOf(TextFieldValue()) }
            var textState3 by remember { mutableStateOf(TextFieldValue()) }
            var textState4 by remember { mutableStateOf(TextFieldValue()) }

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                modifier = Modifier
                    .fillMaxWidth()
            )

            TextField(
                value = textState2,
                onValueChange = { textState2 = it },
                label = { Text(text = "Put your name here") },
                modifier = Modifier
                    .width(250.dp)
                    .wrapContentHeight(align = Alignment.CenterVertically)
                ,
                maxLines = 5
            )

            TextField(
                value = textState3,
                onValueChange = { textState3 = it },
                label = { Text(text = "Put your name here") },
                modifier = Modifier
                    .requiredWidth(315.dp)
                    .height(150.dp)
            )

            OutlinedTextField(
                value = textState4,
                onValueChange = { textState4 = it },
                label = { Text(text = "Put your name here") },
                modifier = Modifier
                    .fillMaxWidth(0.8F)
                    .height(100.dp)
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField hint

Compose TextField Hint
The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text.

TextField widget constructor has no argument named ‘hint’. But we put a title for this tutorial as ‘TextField hint’? So, what is a hint, and why do we use it for a widget? Hint means to instruct users on what should they do in this widget. Such as a hint for a DropdownMenu widget may be ‘select an item’ and a hint for TextField is ‘put your age here’ to collect the user's age in the specified TextField widget.

The following jetpack compose tutorial will demonstrate how we can display a hint like text/message to the user for a TextField. There are two ways to show a text message to the users inside a TextField layout. One is the TextField constructor’s ‘label’ argument and another one is the ‘placeholder’ argument.

The TextField label argument is optional and displayed inside the TextField container. So we can show a message as a hint to the user about what they should enter in this TextField and how to format the text. Such as, we can collect user email on a TextField and show a label to the user like ‘Input your email address here’. Then this label will act as a hint for this TextField.

The TextField constructor’s ‘placeholder’ argument is also optional. The placeholder is displayed when the TextField is in a focused state and it is empty. So, we can also show a hint message to the user about what they should input in this TextField or what is the rule to put valid text here.

The interesting part of these ‘label’ and ‘placeholder’ arguments is that they both accept composable objects. So we can pass an icon with a text message to this argument. We can show custom colors for these objects. As a result, TextField can display both icon and text for a label or placeholder that acts like a hint.

This jetpack compose tutorial is written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we show a hint to the user for a specified TextField widget. We also displayed screenshots of this tutorial’s emulator output screen.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                placeholder = { Text(text = "Name")}
            )

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                colors = TextFieldDefaults.textFieldColors(
                    placeholderColor = Color.Blue,
                    disabledPlaceholderColor = Color.Red
                ),
                placeholder = {
                    Text(
                        text = "Name",
                        fontWeight = FontWeight.Bold
                    )
                }
            )

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Type to search") },
                placeholder = {
                    Row {
                        Text(
                            text = "Search Word",
                            fontWeight = FontWeight.Bold
                        )
                        Icon(
                            imageVector = Icons.Filled.Search,
                            contentDescription = "Localized description"
                        )
                    }
                }
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Find favorite book") },
                placeholder = {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text(
                            text = "Book Name",
                            fontWeight = FontWeight.Bold
                        )
                        Icon(
                            imageVector = Icons.Filled.Favorite,
                            contentDescription = "Localized description",
                            tint = Color.Blue
                        )
                    }
                }
            )

            OutlinedTextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedLabelColor = Color.Green,
                    unfocusedLabelColor = Color.Blue,
                    disabledLabelColor = Color.DarkGray,
                    errorLabelColor = Color.Red,
                    placeholderColor = Color.Blue,
                    disabledPlaceholderColor = Color.Magenta
                ),
                placeholder = { Text(text = "Name")}
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField background color

Compose TextField Background Color
Text is the main thing of any application. The jetpack compose makes it easier for the android application developer to display text, enter text and modify text. To write text inside an android application the jetpack compose library provides a widget name TextField. Displaying and managing a TextField widget is very easy in jetpack compose.

Sometimes android app developers need to change the default background color of a TextField widget in jetpack compose. Changing the TextField background color is a little bit difficult. We can’t directly put a color for any property of the TextField widget to change its background color.

This android application development tutorial will demonstrate to us how we can change the TextField background color in jetpack compose. TextField has a property/parameter/argument named ‘colors’. Here we can assign some values to change the TextField default colors such as background color, text color, cursor color, placeholder color, disabled text color, error label color, etc.

So, we can change the jetpack compose TextField background color by assigning its ‘colors’ property value. The ‘colors’ property value overrides the TextField default colors backgroundColor. This backgroundColor property value will show in our TextField as its background color. The following jetpack compose kotlin code and rendered screenshot will help you to better understand the thing.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color(0xFFFFB7C5)
                )
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField remove underline

Compose TextField Remove Underline
The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text.

The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField.

The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc.

Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorColor, focusedIndicatorColor, unfocusedIndicatorColor, disabledIndicatorColor, errorIndicatorColor, leadingIconColor, etc.

The arguments named with ‘indicator’ means the underline of the TextField widget. So we can change the underline color of the TextField widget using those indicator colors. We can simply hide the underline from a TextField by setting a transparent color to those. Practically, we do not remove the underline from TextField, we only hide the underline from a TextField widget by setting its color value to transparent.

Jetpack developers can hide the underline from its focused state using the ‘focusedIndicatorColor’ argument. To hide underline from its unfocused state we can use the ‘unfocusedIndicatorColor’ argument value. The ‘disabledIndicatorColor’ allows us to hide TextField underline on its disabled state. And the ‘errorIndicatorColor’ allows setting an underline color for the TextField error state. We have to set the value of those colors to a transparent color.

This jetpack compose tutorial is written in an android studio IDE. Copy the code and run it on an emulator device or a real device to test how we hide the underline from a TextField widget. We also displayed screenshots of this tutorial’s emulator screen.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    disabledIndicatorColor = Color.Transparent,
                    errorIndicatorColor = Color.Transparent
                ),
                enabled = true,
                isError = false
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - TextField request focus

Compose TextField Request Focus
The TextField is a text input widget of android jetpack compose library. Android app users can modify text using the TextField widget. Jetpack compose TextField is an equivalent of the android view system EditText widget. An android app screen can contain multiple TextField widgets to collect user data. So, how we can focus on a specific TextField widget programmatically?

This android jetpack compose tutorial will demonstrate how we can focus a TextField widget in code. The ‘FocusRequester’ object is used in conjunction with ‘Modifier.focusRequester’ to send requests to change focus. So, we can use this Modifier object’s ‘focusRequester’ element to set the focus on a TextField widget programmatically.

The modifier ‘focusRequester()’ function has a required argument name ‘focusRequester’ and its data type is FocusRequester. So that we have to pass a FocusRequester object to this function to make it workable.

At the beginning of this tutorial, we create an instance of the FocusRequester object by calling the FocusRequester() function. Then we assign this FocusRequester instance to the TextField modifier ‘focusRequester()’ function argument value. Now we have a TextField with a FocusRequester instance.

Next, we call this FocusRequester object’s requestFocus() method by a Button click event to request TextField focus programmatically. Finally, we can use this FocusRequester.requestFocus() method to set focus on the TextField widget from any event.

This tutorial code is written in an android studio IDE, so you can copy the code and paste it into your android studio IDE main activity file to check how our code work in an emulator device or in a physical android device. Screenshots are also displayed at the bottom of the code snippets. Look at those to understand the code efficiently.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.TextFieldValue
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(){
        Column(
            Modifier
                .background(Color(0xFFEDEAE0))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            var textState by remember { mutableStateOf(TextFieldValue()) }
            val focusRequester = FocusRequester()

            TextField(
                value = textState,
                onValueChange = { textState = it },
                label = { Text(text = "Put your name here") },
                modifier = Modifier.focusRequester(focusRequester),
            )

            Button(onClick = {
                focusRequester.requestFocus()
            }) {
                Text(text = "Focus On TextField")
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials

jetpack compose - Button elevation

Compose Button Elevation
The Button is a primary component of an android application. Android application developers can’t imagine an application without a Button widget. In the jetpack compose library there are several types of Button widgets such as Button, TextButton, FloatingActionButton, OutlinedButton, IconButton, etc,

Android application developers used them in their app user interface for various requirements. Such as an IconButton shows an Icon inside it with a clickable functionality. TextButton displays a clickable simple Text object. By default, TextButton has no elevation. The Button widget has an elevation but we can change its elevation value.

This android application development tutorial will demonstrate to us how we can set or change a Button widget elevation in jetpack compose. In this example, we will set or change Button, TextButton, and OutlinedButton’s elevation size/value. We also change the TextButton’s different states elevations such as default elevation, pressed elevation, and disabled elevation.

To do that we put a Column widget inside our composable function and then place some Button widgets inside this vertical layout such as Button, TextButton, and OutlinedButton. The Button widget has an argument/parameter/property named ‘elevation’.

We have to pass a ‘ButtonDefaults.elevation’ object for this ‘elevation’ parameter. This ‘ButtonDefaults.elevation’ object overrides the default elevations used in a Button widget such as default elevation, pressed elevation, disabled elevation, hovered elevation, and focused elevation. We can set those elevations by putting values for those parameters. The following example code and screenshot will describe things more effectively.
MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
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(){
        Column(
            Modifier
                .background(Color(0xFFFFFFFF))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            Button(
                onClick = {
                    // do something here
                },
                shape = RoundedCornerShape(8.dp),
                elevation = ButtonDefaults.elevation(
                    defaultElevation = 6.dp,
                    pressedElevation = 8.dp,
                    disabledElevation = 0.dp
                )
            ) {
                Text(
                    text = "Elevation 6 DP",
                    modifier = Modifier.padding(12.dp)
                )
            }

            Button(
                onClick = {
                    // do something here
                },
                shape = RoundedCornerShape(8.dp),
                elevation = ButtonDefaults.elevation(
                    defaultElevation = 6.dp,
                    pressedElevation = 8.dp,
                    disabledElevation = 0.dp
                ),
                enabled = false
            ) {
                Text(
                    text = "Disabled Elevation 0 DP",
                    modifier = Modifier.padding(12.dp)
                )
            }

            TextButton(
                onClick = {
                    // do something here
                },
                shape = RoundedCornerShape(8.dp),
                elevation = ButtonDefaults.elevation(
                    defaultElevation = 1.dp,
                    pressedElevation = 0.dp,
                    disabledElevation = 0.dp
                ),
                enabled = true
            ) {
                Text(
                    text = "Elevation 1 DP",
                    modifier = Modifier.padding(12.dp)
                )
            }

            OutlinedButton(
                onClick = {
                    // do something here
                },
                shape = CircleShape,
                elevation = ButtonDefaults.elevation(8.dp)

            ) {
                Text(
                    text = "Elevation 8 DP",
                    modifier = Modifier.padding(12.dp)
                )
            }
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
More android jetpack compose tutorials