avatarAnand Gaur

Summary

The provided content is a comprehensive guide on using modifiers in Jetpack Compose to customize UI elements in Android applications.

Abstract

Jetpack Compose modifiers are essential tools for developers to enhance and modify the appearance, layout, and behavior of composables. The guide explains how modifiers can be used to change the size and alignment of UI elements, add borders and background colors, and handle user interactions like clicks. It also covers the use of padding for spacing, the implementation of width and height constraints, and the application of visual effects such as opacity and rotation. Advanced concepts like weight distribution in layouts and clipping shapes are discussed, offering insights into creating responsive and visually appealing interfaces with Jetpack Compose.

Opinions

  • Modifiers in Jetpack Compose are likened to decorators, suggesting they are a flexible and powerful way to alter composables.
  • The guide emphasizes the importance of modifiers for adding accessibility features and processing user input.
  • The use of modifiers for both padding and margin in Jetpack Compose indicates a streamlined approach to UI spacing compared to traditional XML layouts.
  • The guide suggests that using weight with modifiers is a preferred method for creating flexible and proportionate layouts.
  • The inclusion of code examples and explanations for each modifier implies that the author values practical demonstrations for learning purposes.
  • The mention of the default availability of certain modifiers, such as fillMaxWidth and fillMaxHeight, hints at Jetpack Compose's design philosophy of providing sensible defaults for common use cases.
  • The guide's discussion on the alpha modifier for opacity and the rotate modifier for rotation implies that these visual effects are straightforward to implement and can significantly enhance the user experience.
  • The note about the weight modifier being available from Compose version 1.0.0 onwards suggests that the guide is written with an awareness of the evolution of Jetpack Compose and its features.

Modifiers In Jetpack Compose

Modifiers:

Modifiers are the fundamental building blocks for customizing and enhancing your composables in Jetpack Compose.

It act s like decorators so that

  • Change the composable’s size, layout, behavior, and appearance
  • Add information, like accessibility labels
  • Process user input
  • Add high-level interactions, like making an element clickable, scrollable, draggable, or zoomable
@Composable
private fun Greeting(name: String) {
    Column(modifier = Modifier.padding(24.dp)) {
        Text(text = "Hello,")
        Text(text = name)
    }
}

Controlling size & layout:

Modifier.fillMaxSize(): Acts like Match Parents in XML

Modifier.size(400.dp): Used to give the specific size

Modifier.fillMaxWidth(): Used for taking complete width

Modifier.fillMaxHeight(): Used for taking complete height

Modifier.padding(20.dp): For adding the padding

Modifier.align(alignment = Alignment.End): For give alignment like

Controlling Appearance:

Modifier.border(10.dp, Color.Yellow): used for adding border

Modifier.background(Color.Red): for background

To make a text Clickable:

Text(text = "Click me!",
        modifier = Modifier.clickable
        {
            Toast.makeText(
                context, "Text clicked!",
                Toast.LENGTH_SHORT
            ).show()
        })

Adding image:

 @Composable
    fun Addimage(name: String) {
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = null
        )
    }

Row:

Used to arrange UI elements horizontally side-by- side.

Row(
        horizontalArrangement = Arrangement.End,
        modifier = Modifier.size(400.dp)
    )
    {
        Text(
            text = "Hello$name!",
            color = Color.Blue,
            fontSize = 30.sp,
        )
        Text(
            text = "Someothertext",
            color = Color.Blue, fontSize = 30.sp
        )
    }

Column:

Used to arrange UI elements vertically one below the other.

  Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = Modifier.size(400.dp)
    )
    {
        Text(
            text = "Hello $name!",
            color = Color.Blue,
            fontSize = 30.sp
        )
        Text(
            text = "Some other text",
            color = Color.Blue,
            fontSize = 30.sp
        )
    }

Box:

Used to stack Ul elements on top of each other.

 Box(modifier = Modifier.size(400.dp))
    {
        Text(
            text = "Hello $name!",
            color = Color.Blue, fontSize = 30.sp
        )

        Text(
            text = "Some other text",
            color = Color.Blue, fontSize = 30.sp
        )

    }

Background Color:

Text("Text with green background color",
            Modifier.background(color = Color.Green))

Padding:

Jetpack compose doesn’t have a modifier for margin. We should use the padding modifier for both padding and margin.

@Composable
fun TextWidthPadding() {
    Text(
        "Padding and margin!",
        Modifier.padding(32.dp) // Outer padding (margin)
            .background(color = Color.Green) //background color
            .padding(16.dp) // Inner padding
    )
}

Width and Height:

For width you need to use width(value : Dp)

For height you need to use height(value: Dp)

@Composable
fun WidthAndHeightModifier() {
    Text(
        text = "Width and Height",
        color = Color.White,
        modifier = Modifier
            .background(Color.Blue)
            .width(200.dp)
            .height(300.dp)
    )
}

Size:

If you need both width and height in same modifier, use Modifier.size().

If both width and height are same, use this Modifier.size(size: Dp). example: Modifier.size(200.dp)

If you want different width and height, use Modifier.size(width: Dp,height:Dp) example: Modifier.size(width=200.dp,height=100.dp)

@Composable
fun SizeModifier() {
    Text(
        text = "Text with Size",
        color = Color.White,
        modifier = Modifier
            .background(Color.Cyan)
            .size(width = 250.dp, height = 100.dp)
    )
}

Fill Max Width:

You need to pass the fraction size. It should be 0.0 to 1.0.

If you want the width as match_parent you can use 1.0.

Its default value is 1.0. If you call the method without a fraction size, it will set as 1.0

0.0 means 0% 0.1 means 10% 1.0 means 100%

If there is no view in the horizontal area: If you give 1.0 -> it will occupy entire width (match_parent).

If you give any other fraction values -> it will occupy based on the fraction value. For example, if you give 0.75 fraction, it occupies 75% of screen width.

If some views already exist:

If you give 1.0 -> it will occupy the rest of the balance space(fill the balance area).

If you give any other fractional values -> it will fill the fraction percentage in the balance space.

Composable
fun FillWidthModifier() {
    Text(
        text = "Text Width Match Parent",
        color = Color.White,
        modifier = Modifier
            .background(Color.Gray)
            .padding(Dp(10f))
            .fillMaxWidth(1f))
}

Fill Max Height:

You need to pass the fraction size. It should be 0.0 to 1.0.

If you want the height as match_parent you can use fillMaxHeight(1.0).

If there is no view in the vertical area:

If you give 1.0 -> it will occupy the entire height (match_parent).

If you give any other fraction values -> it will occupy based on the fraction value. For example, if you give 0.75 fraction it will occupy 75% of the screen height .

If some views already exist:

If you give 1.0 -> it will occupy the rest of the balance space(fill the balance area). If you give any other frictional values -> it will fill the fraction percentage in the balance space.

@Composable
fun FillHeightModifier() {
    Text(
        text = " Text with 75% Height ",
        color = Color.White,
        modifier = Modifier
            .background(Color.Green)
            .fillMaxHeight(0.75f) //75% area fill
    )
}

We can also use the following modifiers:

fun MinWidth(value: Dp): LayoutModifier//Minimum width

fun MaxWidth(value: Dp): LayoutModifier//Maximum width

fun MinHeight(value: Dp): LayoutModifier//Minimum height

fun MaxHeight(value: Dp): LayoutModifier//Maximum height

Alpha (Opacitiy):

Alpha is used to set the opacity of the view.

Modifier.alpha(alpha: Float)

You can use 0.1 to 1.0.

0.0 means 0% 0.1 means 10% 1.0 means 100%

@Composable
fun AlphaModifier() {
    Box(
        Modifier
            .size(250.dp)
            .alpha(0.5f)//50% opacity
            .background(Color.Red)
    )
}

Rotate:

Sets the degrees the view is rotated around the center of the composable. Increasing values result in clockwise rotation. Negative degrees are used to rotate in the counterclockwise direction.

Modifier.rotate(degrees: Float)

@Composable
fun RotateModifier() {
    Box(
        Modifier
            .rotate(45f)
            .size(250.dp)
            .background(Color.Red)
    )
}

Scale:

Scale the contents of the composable by the following scale factors along the horizontal and vertical axis respectively. Negative scale factors can be used to mirror content across the corresponding horizontal or vertical axis.

@Composable
fun ScaleModifier() {
    Box(
        Modifier
            .scale(scaleX = 2f, scaleY = 3f)
            .size(200.dp, 200.dp)
    )
}

Weight:

With weight, you can specify a size ratio between multiple views.

For example: If you add the view1 with weight 1, view2 with weight 1, view3 with weight 2.

It will sum the all weights 1+1+ 2 = 4 and allocate the space for the view based on given weight. View1 gets 25% space → 1/4*100=25%

View1 gets 25% space → 1/4*100=25%

View3 gets 50% space → 2/4*100=50%

Check following code and output for understanding.

@Composable
fun WeightModifier(){
    Row() {
        Column(
            Modifier.weight(1f).background(Color.Red)){
            Text(text = "Weight = 1", color = Color.White)
        }
        Column(
            Modifier.weight(1f).background(Color.Blue)){
            Text(text = "Weight = 1", color = Color.White)
        }
        Column(
            Modifier.weight(2f).background(Color.Green)
        ) {
            Text(text = "Weight = 2")
        }

    }
}

Note: Weight is available from compose 1.0.0 version. If you are using beta version, it is unavailable.

Border:

You can set the border by the following ways:

  1. Modifier.border(width: Dp, color: Color, shape: Shape = RectangleShape)
  2. Modifier.border(width: Dp, brush: Brush, shape: Shape)
  3. Modifier.border(border: BorderStroke, shape: Shape = RectangleShape)
  4. Modifier.border(width: Dp, color: Color, shape: Shape = RectangleShape)

Here the shape parameter is optional. If you do not pass this parameter, it will set a rectangle as a default.

This example uses the default:

@Composable
fun BorderModifier() {
    Text(
        text = "Text with Red Border",
        modifier = Modifier
            .padding(10.dp)
            .background(Color.Yellow)
            .border(2.dp,Color.Red)
            .padding(10.dp)
    )
}

Modifier.border(width: Dp, brush: Brush, shape: Shape)

Here we set the rounded corner shape border.

width — we set 2dp

brush — We use SolidColor()

RoundedCornerShape() — It’s inbuilt shape in jetpack compose. We use this shape to achieve the rounded corner border.

@Composable
fun BorderWithShape() {
    Text(
        text = "Text with round border",
        modifier = Modifier
            .padding(10.dp)
            .border(2.dp, SolidColor(Color.Green),                                  RoundedCornerShape(20.dp))
            .padding(10.dp)
    )

}

Clip:

Clip modifier allows you to clip the existing shape. You can use a default shape or your customized shapes.

Available shapes in Jetpack Compose:

  • RectangleShape
  • CircleShape
  • RoundedCornerShape
  • CutCornerShape

In this example we use the RoundedCornerShape.

@Composable
fun ClipModifier() {
    Text(
        text = "Text with Clipped background",
        color = Color.White,
        modifier = Modifier
            .padding(Dp(10f))
            .clip(RoundedCornerShape(25.dp))
            .background(Color.Blue)
            .padding(Dp(15f))
    )
}
Jetpack Compose
Compose
Compose Ui
Android
Kotlin
Recommended from ReadMedium