Custom Chips using Jetpack Compose in Android - GeeksforGeeks

21 Nov, 2021
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going to implement this project using the Kotlin language. 
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.Buttonimport androidx.compose.material.MaterialThemeimport androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContent {            JetpackComposePracticeTheme {                // A surface container using                  // the 'background' color from the theme                Surface(color = Color.White) {                    Column(modifier = Modifier.padding(10.dp)) {                        // call the function which                          // contains all the chips                        Chips()                    }                }            }        }    }} // Function for Custom Chip// Later we will reuse it to// create chips wherever needed// selected : Boolean - to Check// whether it is checked or not// text - To show the data@Composablefun CustomChip(    selected: Boolean,    text: String,    modifier: Modifier = Modifier) {    // define properties to the chip    // such as color, shape, width    Surface(        color = when {            selected -> MaterialTheme.colors.onSurface            else -> Color.Transparent        },        contentColor = when {            selected -> MaterialTheme.colors.onPrimary            else -> Color.LightGray        },        shape = CircleShape,        border = BorderStroke(            width = 1.dp,            color = when {                selected -> MaterialTheme.colors.primary                else -> Color.LightGray            }        ),        modifier = modifier    ) {        // Add text to show the data that we passed        Text(            text = text,            textAlign = TextAlign.Center,            style = MaterialTheme.typography.body2,            modifier = Modifier.padding(8.dp)        )     }} // Function to create a Custom Image Chip with text// text - For showing data on the chip// imageId - For showing the image that we want to use// selected : Boolean - to check if it is selected or not@Composableprivate fun CustomImageChip(    text: String,    imageId: Int,    selected: Boolean,    modifier: Modifier = Modifier) {    // define properties to the chip    // such as color, shape, width    Surface(        color = when {            selected -> MaterialTheme.colors.primary            else -> Color.Transparent        },        contentColor = when {            selected -> MaterialTheme.colors.onPrimary            else -> Color.LightGray        },        shape = RoundedCornerShape(16.dp),        border = BorderStroke(            width = 1.dp,            color = when {                selected -> MaterialTheme.colors.primary                else -> Color.LightGray            }        ),        modifier = modifier    ) {        // Inside a Row pack the Image and text together to        // show inside the chip        Row(modifier = Modifier) {            Image(                painter = painterResource(imageId),                contentDescription = null,                modifier = Modifier                    .padding(8.dp)                    .size(20.dp)                    .clip(CircleShape)            )            Text(                text = text,                style = typography.body2,                modifier = Modifier.padding(end = 8.dp, top = 8.dp, bottom = 8.dp)            )        }    }} @Preview@Composablefun Chips() {    Text(text = "Custom Chips", style = typography.h6, modifier = Modifier.padding(8.dp))    SubtitleText(subtitle = "Custom chips with surface")    // Call the functions that we defined      // above and pass the actual data    Column {        Row(modifier = Modifier.padding(8.dp)) {            // creates a custom chip for active state            CustomChip(                selected = true,                text = "Chip",                modifier = Modifier.padding(horizontal = 8.dp)            )            // Creates a custom chip for inactive state            CustomChip(                selected = false,                text = "Inactive",                modifier = Modifier.padding(horizontal = 8.dp)            )            // Create a custom image chip whose state is active            CustomImageChip(                text = "custom",                imageId = R.drawable.gfg_logo,                selected = true            )            Spacer(modifier = Modifier.padding(8.dp))            // Create a custom image chip whose state is inactive            CustomImageChip(                text = "custom2",                imageId = R.drawable.gfg_logo,                selected = false            )        }        SubtitleText(subtitle = "Buttons with circle clipping.")        // We can also use a circular shape button as a chip        Row(modifier = Modifier.padding(8.dp)) {            // Creates an active state chip using button            Button(                onClick = {},                modifier = Modifier                    .padding(8.dp)                    .clip(CircleShape)            ) {                Text(text = "Chip button")            }            // Creates an inactive state chip using button            Button(                onClick = {},                enabled = false,                modifier = Modifier                    .padding(8.dp)                    .clip(CircleShape)            ) {                Text(text = "Disabled chip")            }        }    }} // Function to show a text message@Composablefun SubtitleText(subtitle: String, modifier: Modifier = Modifier) {    Text(text = subtitle, style = typography.subtitle2, modifier = modifier.padding(8.dp))}
 
 
Output:
 
 
sagar0719kumar
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters