To replicate the provided XML layout using Jetpack Compose, we can use a combination of Column
, Row
, and LazyColumn
or LazyRow
for the table structure. Here’s how you can achieve the same:
Jetpack Compose Code:
@Composable
fun EmployeeTable() {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
// Title
Text(
text = "Employee data",
style = MaterialTheme.typography.h6,
modifier = Modifier.padding(bottom = 16.dp)
)
// Table Header
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color(0xFFCDDC39))
.padding(8.dp)
) {
TableCell("S NO", Modifier.weight(1f))
TableCell("NAME", Modifier.weight(1f))
TableCell("MOBILE", Modifier.weight(1f))
TableCell("EMAIL", Modifier.weight(1f))
}
// Table Rows
val employees = listOf(
Employee(1, "Hari", "8762432", "hari@gmail.com"),
Employee(2, "Sproothi", "87682463", "sproothi@gmail.com"),
Employee(3, "Raj", "87383757834", "raj@yamil.com"),
Employee(4, "Durga", "987835", "durgasoft@gmail.com"),
Employee(5, "Soft", "7767", "sift@gmail.com")
)
employees.forEach { employee ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
TableCell(employee.sno.toString(), Modifier.weight(1f))
TableCell(employee.name, Modifier.weight(1f))
TableCell(employee.mobile, Modifier.weight(1f))
TableCell(employee.email, Modifier.weight(1f))
}
}
}
}
@Composable
fun TableCell(text: String, modifier: Modifier = Modifier) {
Text(
text = text,
style = MaterialTheme.typography.body1,
modifier = modifier
.padding(8.dp)
.border(1.dp, Color.Gray)
.padding(8.dp) // Inner padding
)
}
data class Employee(
val sno: Int,
val name: String,
val mobile: String,
val email: String
)
Explanation:
- Title:
- A simple
Text
Composable for the “Employee data” title.
- Header Row:
- A
Row
withTableCell
composables for each column header. Modifier.weight()
ensures equal distribution of space across the cells.
- Employee Rows:
- Created using a list of
Employee
data objects. - Each row is rendered using a
Row
andTableCell
.
- TableCell:
- A reusable composable for rendering text with padding and a border.
- Styling:
- Used
Modifier.border()
for cell borders. Modifier.weight()
ensures cells in each row have the same width.
- Data Representation:
- Employee data is stored in a
data class
and rendered dynamically using aforEach
loop.
How to Use:
- Add
EmployeeTable()
to yoursetContent
block in theMainActivity
. - Jetpack Compose will render a responsive table layout with borders and proper styling.
Would you like additional enhancements like clickable rows or dynamic data?