user1865027
user1865027

Reputation: 3647

How to apply opacity to all of its children in Android Compose?

I have a Row that contains a circle Image. A Column with 2 BasicText in there and a Spacer between Column and Image. I want to have a way to "highlight" this row by giving it a blue tint with some opacity overlay. The closest I can get is by giving the Row a background color, but it doesn't give all the children blue-ish tint. I know background will not work because the color isn't drawn overlay but instead behind all other elements. Is there a way to achieve this? Thanks!

enter image description here

Upvotes: 3

Views: 3833

Answers (2)

MyeongHwan Kim
MyeongHwan Kim

Reputation: 21

You could do what you need in simple way.

@Composable
fun TestRow(modifier: Modifier = Modifier) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(color = Color.Blue)
            .alpha(0.5f)        // this is the answer
    ) {
        Image()

        Spacer(modifier = modifier.width(8.dp))
        
        Column {
            Text()

            Text()
        }
    }
}

Alpha value in Parent composable will affect to it's children.

Upvotes: 1

F.Mysir
F.Mysir

Reputation: 4176

The best way I can think of is the following:

YourActivityTheme {
    // A surface container using the 'background' color from the theme
    Surface(
        modifier = Modifier.wrapContentSize(),
        color = MaterialTheme.colors.background
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(IntrinsicSize.Min)
                .padding(8.dp),
            shape = RoundedCornerShape(12.dp),
            border = BorderStroke(2.dp, Color.Black)
        ) {
            Row(Modifier.padding(8.dp)) {
                Surface(
                    modifier = Modifier.size(50.dp),
                    shape = CircleShape,
                    border = BorderStroke(2.dp, Color.Black),
                    color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f)
                ) {
                    // Image goes here
                }
                Column(
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .align(Alignment.CenterVertically)
                ) {
                    Text("Text1", fontWeight = FontWeight.Bold)
                    Text("Text2", style = MaterialTheme.typography.body2)
                }
            }

            Box(modifier = Modifier
                .fillMaxSize()
                .alpha(0.2f)
                .background(Color.Blue))
        }
    }
}

There are endless ways you can create your example. That one is the best that comes to my mind. If you have any question please fill free to ask me!

Upvotes: 2

Related Questions