3
3
.
.
1
1
.
.
3
3
C
C
r
r
e
e
a
a
t
t
e
e
C
C
u
u
s
s
t
t
o
o
m
m
C
C
o
o
n
n
t
t
a
a
i
i
n
n
e
e
r
r
I
I
n
n
f
f
o
o
[
[
R
R
]
]
This tutorial shows how to create a custom Container using Composable Function that takes @Composable as Parameter.
Such Input Parameter can accepts one or more Views
C
C
u
u
s
s
t
t
o
o
m
m
S
S
u
u
r
r
f
f
a
a
c
c
e
e
In this example we create YellowSurface Custom Container that can take a single View.
This way we can customize Surface container once and then use it as needed.
MainActivity.kt
package com.example.testcompose
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.preferredSize
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.unit.dp
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
YellowSurface{
Text("John")
}
}
}
}
@Composable
fun YellowSurface(content: @Composable () -> Unit) {
Surface(
modifier = Modifier.preferredSize(50.dp),
color = Color.Yellow
) {
content()
}
}
Output
C
C
u
u
s
s
t
t
o
o
m
m
C
C
o
o
l
l
u
u
m
m
n
n
In this example we create CenteredYellowColumn as customizes Column with yellow background and centered Views.
This Custom Container also has additional parameter title which is used to place additional Text View at the top.
MainActivity.kt
package com.example.testcompose
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CenteredYellowColumn(title = "People") {
Text("John")
Text("Bob")
Text("Susan")
}
}
}
}
@Composable
fun CenteredYellowColumn(title: String, content: @Composable () -> Unit) {
Surface(color = Color.Yellow) {
Column(
Modifier.fillMaxSize(),
horizontalGravity = Alignment.CenterHorizontally
) {
Text(title, fontWeight= FontWeight.Bold, fontSize = 20.sp)
content()
}
}
}
Output