使用Android Jetpack Compose的Grid组件可以创建一个类似网格的视图。
首先,在build.gradle文件中添加Jetpack Compose依赖项:
dependencies {
def compose_version = "1.0.1"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.material:material-icons-core:$compose_version"
implementation "androidx.compose.material:material-icons-extended:$compose_version"
}
然后,可以使用LazyVerticalGrid
组件创建一个具有类似网格的视图。下面的示例代码展示了如何使用LazyVerticalGrid
展示一个包含20个不同颜色的正方形的网格:
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun GridScreen() {
LazyVerticalGrid(
cells = GridCells.Fixed(3),
modifier = Modifier.padding(16.dp)
) {
itemsIndexed(colors) { index, color ->
GridItem(color)
}
}
}
@Composable
fun GridItem(color: Color) {
Card(
modifier = Modifier.padding(8.dp)
) {
MaterialTheme {
Card(
modifier = Modifier
.size(80.dp)
.background(color)
) {}
}
}
}
val colors = listOf(
Color.Red, Color.Blue, Color.Green, Color.Yellow, Color.Gray,
Color.Magenta, Color.Cyan, Color.DarkGray, Color.LightGray, Color.Black,
Color.Red, Color.Blue, Color.Green, Color.Yellow, Color.Gray,
Color.Magenta, Color.Cyan, Color.DarkGray, Color.LightGray, Color.Black
)
在这个例子中,我们创建了一个LazyVerticalGrid
,将每个单元格大小都