练习:Compose 基础知识
@Composable
fun ComposeArticleApp() {
val img = painterResource(id = R.drawable.bg_compose_background)
ArticleCard(
img, stringResource(R.string.jetpack_compose_tutorial),
stringResource(R.string.short_description), stringResource(id = R.string.compose_long_desc)
)
}
@Composable
private fun ArticleCard(imagePainter: Painter, title: String, shortDescription: String,longDescription:String) {
Column {
//设置图片宽度充满屏幕、高度150dp、缩放模式充满父容器
Image(
painter = imagePainter, contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = Modifier
.fillMaxWidth()
.height(150.dp)
)
Text(text = title, fontSize = 24.sp, modifier = Modifier.padding(16.dp))
//设置文字两端对齐、距离内边左右16dp
Text(
text = shortDescription,
textAlign = TextAlign.Justify,
modifier = Modifier
.padding(start = 16.dp, end = 16.dp),
)
Text(text = longDescription, textAlign = TextAlign.Justify, modifier = Modifier.padding(16.dp))
}
}
1.在屏幕上垂直和水平居中对齐所有内容。
2.将第一个 Text 可组合项的字体粗细设为 Bold,top 方向内边距设为 24dp,bottom 方向内边距设为 8dp。
3.将第二个 Text 可组合项的字体大小设为 16sp。
@Composable
fun TaskCompletedScreen() {
val image = painterResource(id = R.drawable.ic_task_completed)
Column(
Modifier
.fillMaxHeight()
.fillMaxWidth(),
verticalArrangement = Arrangement.Center,//子元素垂直居中
horizontalAlignment = Alignment.CenterHorizontally//子元素水平居中
) {
Image(painter = image, contentDescription = null)
Text(
text = stringResource(R.string.all_task_completed),
modifier = Modifier.padding(top = 24.dp, bottom = 8.dp),
fontWeight = FontWeight.Bold
)
Text(
text = stringResource(R.string.nice_work),
fontSize = 16.sp
)
}
}
这里主要就是看一下weight用法权重
@Composable
fun ComposeQuadrantApp() {
Column(Modifier.fillMaxWidth()) {
Row(Modifier.weight(1f)) {
ComposableInfoCard(
stringResource(R.string.first_title),
stringResource(R.string.first_description),
Color(0xFFEADDFF),
Modifier.weight(1f)
)
ComposableInfoCard(
title = stringResource(R.string.second_title),
description = stringResource(R.string.second_description),
backgroundColor = Color(0xFFD0BCFF),
Modifier.weight(1f)
)
}
Row(Modifier.weight(1f)) {
ComposableInfoCard(
title = stringResource(R.string.third_title),
description = stringResource(R.string.third_description),
backgroundColor = Color(0xFFB69DF8),
modifier = Modifier.weight(1f)
)
ComposableInfoCard(
title = stringResource(R.string.fourth_title),
description = stringResource(R.string.fourth_description),
backgroundColor = Color(0xFFF6EDFF),
modifier = Modifier.weight(1f)
)
}
}
}
@Composable
fun ComposableInfoCard(
title: String, description: String,
backgroundColor: Color,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.background(backgroundColor)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = title, fontWeight = FontWeight.Bold, modifier =Modifier.padding(bottom = 16.dp))
Text(text = description)
}
}