文章

Jetpack Compose:按钮组件

一、Button

1.基本按钮

Button 默认没有任何样式,仅仅是一个点击事件响应组件,需要在 content 参数中使用其他组件来实现 Button。

Button(
    onClick = {}
) {
    Text(text = "Hello")
}

buttonCompose_1

2.按钮添加图标

在 Text 前面加入 Icon 组件可以添加图标。

Button(
    onClick = {}
) {
    Icon(
        imageVector = Icons.Filled.Done,
        contentDescription = null,
        modifier = Modifier.padding(end = ButtonDefaults.IconSpacing)
    )
    Text(text = "Done")
}

buttonCompose_2

3.监听事件

button 有一个参数 interactionSource,此参数也出现在其他组件中,它是用来监听组件状态的事件源,通过它我们就可以根据组件的状态设置不同样式,如下所示:

val interactionSource = remember { MutableInteractionSource() }
var text by remember { mutableStateOf("未按下") }
// 判断是否处于按下状态
val pressState = interactionSource.collectIsPressedAsState()
text = if (pressState.value) {
    "已按下"
} else {
    "未按下"
}
Button(
    onClick = {},
    interactionSource = interactionSource
) {
    Icon(
        imageVector = Icons.Filled.Done,
        contentDescription = null,
        modifier = Modifier.padding(end = ButtonDefaults.IconSpacing)
    )
    Text(text = text)
}

上面例子展示了按钮在正常状态下显示 “未按下”,在选中状态下显示 “已按下”。

interactionSource 有以下四种状态:

interactionSource 判断状态 功能
interactionSource.collectIsPressedAsState() 判断是否按下
interactionSource.collectIsFocusedAsState() 判断是否获得焦点
interactionSource.collectIsDraggedAsState() 判断是否拖动
interactionSource.collectIsHoveredAsState() 判断是否悬停

二、IconButtton

图标按钮

IconButton(onClick = { /*TODO*/ }) {
    Icon(imageVector = Icons.Filled.Favorite, contentDescription = null)
}

三、FloatingActionButton

1.普通悬浮按钮

FloatingActionButton(onClick = { /*TODO*/ }) {
    Icon(Icons.Filled.Facebook, contentDescription = null)
}

buttonCompose_3

2.文字悬浮按钮

ExtendedFloatingActionButton(
    text = { Text("访问脸书") },
    onClick = { },
    icon = { Icon(Icons.Filled.Facebook, contentDescription = null) }
)

buttonCompose_4

License:  CC BY 4.0