🌑

帮帮技术站

jetpack compose basic

jetpack compose基础

https://gist.github.com/stevdza-san

  1. 基础组件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    Surface
    Column
    Row
    Box
    Text
    Card
    IconButton
    textfiled
    Surface
    Icon
    Image
    lazyColumn
    LazyVerticalGrid
  1. column row

ColumnScope.weightItem

.padding(16.dp) margin
.background(Color.bulue)
.padding(16.dp) padding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Column(
horzontalAlignment=center
verticalArrangement=bottom,top,center,spaceBeteween,spaceEvbenly,spaceAround
modifier=modifier.weight(1f)
)

限制作用域weight才生效
@Composable
fun ColumnScope.weightItem(){
Surface(){
modifier=Modifier.weight(1f)
}
}

  1. box
    contentAligent verticalScroll

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    fun BoxItem(){
    Box(
    modifier=Modifier.background(Color.bule),
    contentAligent=Alignment.TopCenter
    ){
    Box(
    modifier=Modifier.background(Color.bule).height(10.dp).width(10.dp).verticalScroll(rememberState()),
    ){
    Text(text="Ha a android toy ",fontSize=48.sp)
    }
    }
    }


  2. Text
    textAlign=TextAlign.Center
    buildAnnotatedString(){
    append(“A”)
    append(“B”)
    append(“C”)
    }
    withStyle:SpanStyle ParagraphStyle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
基础构建
Text(tex="i love android !",
fontSize = MaterialTheme.typography.h6.fontSize
fontStyle=FontStyle.Italic
fontWeight=FontWeight.Bold
textAligin=TextAligin.Center
)

构建spanString SpanStyle ParagraphStyle
Text(){
buildAnnotatedString(){
withStyle(
style=SpanStyle(
color=MaterialTheme.colors.primary,
fontSize=23.sp,
fontWeight=FontWeight.Blod
)
){
append("A")
}
append("B")
append("C")
}
}


溢出构建
Text(text="hello,world".repeat(20),Maxlines=2,overflow=TextOverflow.Ellipsis)


  1. Text高级
    selection
1
2
3
4
5
6
7
8
9
10
11
12
13
Column(){
SelectionContainer{
Column{
Text(text="hello,world")
DisableSelecttion{
Text(text="hello,world")
}
Text(text="hello,world")

}
}
}

Superscript/Subscript Text
上标和下标对齐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Composable
fun SuperScriptText(
normalText: String,
normalTextFontSize: TextUnit = MaterialTheme.typography.subtitle1.fontSize,
superText: String,
superTextFontSize: TextUnit = MaterialTheme.typography.overline.fontSize,
superTextFontWeight: FontWeight = FontWeight.Normal
) {
Text(text = buildAnnotatedString {
withStyle(
style = SpanStyle(
fontSize = normalTextFontSize
)
) {
append(normalText)
}
withStyle(
style = SpanStyle(
fontSize = superTextFontSize,
fontWeight = superTextFontWeight,
baselineShift = BaselineShift.Superscript
)
) {
append(superText)
}
})
}

  1. Card
    exapandable 可收缩card
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@ExperimentalMaterialApi
@Composable
fun ExpandableCard(
title: String,
titleFontSize: TextUnit = MaterialTheme.typography.h6.fontSize,
titleFontWeight: FontWeight = FontWeight.Bold,
description: String,
descriptionFontSize: TextUnit = MaterialTheme.typography.subtitle1.fontSize,
descriptionFontWeight: FontWeight = FontWeight.Normal,
descriptionMaxLines: Int = 4,
shape: Shape = Shapes.medium,
padding: Dp = 12.dp
) {
var expandedState by remember { mutableStateOf(false) }
val rotationState by animateFloatAsState(
targetValue = if (expandedState) 180f else 0f
)

Card(
modifier = Modifier
.fillMaxWidth()
.animateContentSize(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
),
shape = shape,
onClick = {
expandedState = !expandedState
}
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(padding)
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier
.weight(6f),
text = title,
fontSize = titleFontSize,
fontWeight = titleFontWeight,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
IconButton(
modifier = Modifier
.weight(1f)
.alpha(ContentAlpha.medium)
.rotate(rotationState),
onClick = {
expandedState = !expandedState
}) {
Icon(
imageVector = Icons.Default.ArrowDropDown,
contentDescription = "Drop-Down Arrow"
)
}
}
if (expandedState) {
Text(
text = description,
fontSize = descriptionFontSize,
fontWeight = descriptionFontWeight,
maxLines = descriptionMaxLines,
overflow = TextOverflow.Ellipsis
)
}
}
}
}



  1. text field
    TextFiled
    OutlineTextField
    BasicTextField 适用于定制自定义输入框
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    //标题
    label(){
    Text(text="title")
    }
    //后面icon
    trailingIcon(){
    IconButton(){
    Icon(imageVector=Icons.Filled.Check)
    }
    }
    //前面icon
    leadingIcon(){
    IconButton(){
    Icon(imageVector=Icons.Filled.Email)
    }
    }

    //键盘
    keyboardOption = KeyboardOptions(
    keyboardType=KeyboardType.Email,
    imeAction=ImeAction.Go
    )
    //键盘事件
    keyboardAction=KeyboardAction(
    onSearch = {
    //click done
    }
    )



  1. Surface 容器

参考: https://zhuanlan.zhihu.com/p/404437498

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
copy from internet
@Composable
fun SurfaceShow() {
Surface(
shape = RoundedCornerShape(6.dp),
border = BorderStroke(0.5.dp, Color.Green), // 边框
elevation = 10.dp, // 高度
modifier = Modifier
.padding(10.dp), // 外边距
// color = Color.Black, // 背景色
contentColor = Color.Blue,
) {
Surface(
modifier = Modifier
.clickable { } // 点击事件在 padding 前,则此padding为内边距
.padding(10.dp),
contentColor = Color.Magenta // 会覆盖之前 Surface 设置的 contentColor
) {
Text(text = "This is a SurfaceDemo~")
}
}
}


裁剪,根据 shape 属性描述的形状进行裁剪;
高度,根据 elevation 属性设置容器平面的高度,让人看起来有阴影的效果;
边框,根据 border 属性设置边框的粗细以及色值;
背景,Surface 在 shape 指定的形状上填充颜色。这里会比较复杂一点,如果颜色是 Colors.surface,则会将 LocalElevationOverlay 中设置的 ElevationOverlay 进行叠加,默认情况下只会发生在深色主题中。覆盖的颜色取决于这个 Surface 的高度,以及任何父级 Surface 设置的 LocalAbsoluteElevation。这可以确保一个 Surface 的叠加高度永远不会比它的祖先低,因为它是所有先前 Surface 的高度总和。
内容颜色,根据 contentColor 属性给这个平面的内容指定一个首选色值,这个色值会被文本和图标组件以及点击态作为默认色值使用。当然可以被子节点设置的色值覆盖。

  1. 可以滑动控控件
1
2
3
4
5
6
7
8
9
10
11
12
13
fun SimpleList() {
// 使用 rememberScrollState 保存滚动的位置信息
val scrollState = rememberScrollState()
// Modifier.verticalScroll 可添加竖直方向上的滚动属性
// 使用 Column 的 Modifier.verticalScroll 方法确实可以创建一个可滑动的
// List,但是这种方法在开始时就会将所有 item 全部加载,类似于 ScrollView
Column(Modifier.verticalScroll(scrollState)) {
repeat(100) {
Text(text = "Item #$it")
Divider(color = Color.Blue, thickness = 1.5.dp, startIndent = 10.dp)
}
}
}
  1. ConstraintLayout 约束布局
1
2


  1. ConstraintSet 实现动态适配 横屏和竖屏

    1
    2


  2. sign with google button

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@Composable
fun GoogleButton(
modifier: Modifier = Modifier,
text: String = "Sign Up with Google",
loadingText: String = "Creating Account...",
icon: Int = R.drawable.ic_google_logo,
shape: Shape = Shapes.medium,
borderColor: Color = Color.LightGray,
backgroundColor: Color = MaterialTheme.colors.surface,
progressIndicatorColor: Color = MaterialTheme.colors.primary,
onClicked: () -> Unit
) {
var clicked by remember { mutableStateOf(false) }

Surface(
modifier = modifier.clickable { clicked = !clicked },
shape = shape,
border = BorderStroke(width = 1.dp, color = borderColor),
color = backgroundColor
) {
Row(
modifier = Modifier
.padding(
start = 12.dp,
end = 16.dp,
top = 12.dp,
bottom = 12.dp
)
.animateContentSize(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
painter = painterResource(id = icon),
contentDescription = "Google Button",
tint = Color.Unspecified
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = if (clicked) loadingText else text)
if (clicked) {
Spacer(modifier = Modifier.width(16.dp))
CircularProgressIndicator(
modifier = Modifier
.height(16.dp)
.width(16.dp),
strokeWidth = 2.dp,
color = progressIndicatorColor
)
onClicked()
}
}
}
}


  1. coil image
    异步版本 AsyncImage
    https://coil-kt.github.io/coil/compose/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
fun coilImage(){
Box(modifier=Modifier.height(200.dp).width(200.dp)){
val painter =rememberImagePainter(
data="http://example.com/image.png",
builder={
placehoder(R.drwable.ic_placeholder),
error(R.drwable.error),
crossfade(2000),
transformations(
GrayscaleTransformation(),
//CircleCropTransformation(),
BlurTransformation(LocalContext.current),
RoundCornersTransformation(48.dp)
)

}
)
}

val painterState=painter.state
Image(painter=painter,contentDescription="image")
if(painterState is ImagePainter.State.Loading){
CircularProgressIndicator()
}
}

  1. 密码输入框
    rememberSaveable
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    @Composable
    fun Password(){
    Column(){
    val password by rememberSaveable(mutableStateOf(""))
    val passwordVisibility by remember(mutableStateOf(false))
    val icon = if (passwordVisibility) painterResourcer(R.drawable.visibility) else painterResourcer(R.drawable.unvisibility)

    OutlinedTextField(
    val = password,
    onValueChange = {
    password=it
    },
    placeholder={Text(text="Password")},
    label = { Text(text="Password1")},
    trailingIcon = {
    IconButton(onclick{
    passwordVisibility=!passwordVisibility
    }){
    Icon(
    painter=icon,
    contentDescription="visibility icon"
    }
    },
    keyboardOptions = KeyboardOptions(
    keyboardType =KeyboardOptions.Password
    )
    visualTransformation = if (passwordVisibility) visualTransformation.None else passwordVisualTransformation()
    )
    }
    }

  1. GradientButton 渐变按钮
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
        @Composable
    fun GradientButton(
    text: String,
    textColor: Color,
    gradient: Brush,
    onClick: () -> Unit
    ) {
    Button(
    colors = ButtonDefaults.buttonColors(
    backgroundColor = Color.Transparent
    ),
    contentPadding = PaddingValues(), //去除padding
    onClick = { onClick() })
    {
    Box(
    modifier = Modifier
    .background(gradient)
    .padding(horizontal = 16.dp, vertical = 8.dp),
    contentAlignment = Alignment.Center
    ) {
    Text(text = text, color = textColor)
    }
    }
    }

取色
https://uigradients.com/#CoolBlues

1
2
3
4
5
6
7
8
9
10
11
12
fun preview(){
GradientButton(
text=“Button”,
textColor=Color.white,
gradient=Brush.horizontalGradient(
colors = listOf(
color1,color2
)
)
)
}

— Mar 31, 2023

Search