Jetpack Compose(五)-按钮组件

一、Button按钮

(1)先看下Button的参数:

kotlin 复制代码
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Button(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,      //是否启用按钮
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },   //点击交互的效果
    elevation: ButtonElevation? = ButtonDefaults.elevation(),   //按钮的阴影
    shape: Shape = MaterialTheme.shapes.small,
    border: BorderStroke? = null,
    colors: ButtonColors = ButtonDefaults.buttonColors(),
    contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
    content: @Composable RowScope.() -> Unit
) {...}

Button的第一个参数onClick是必填项,这是其最重要的功能,通过回调响应用户点击事件。最后一个参数content也是一个必填项,也是其最重要的功能之一。ComposeButton默认没有任何UI。仅仅是一个响应onClick的容器,它的UI需要在content中通过其他组件来实现。

ButtononClick在底层是通过覆盖Modifier.clickable实现的,所以不要为Button设置Modifier.clickable,即使设置了,也会因为被onClick覆盖而没有任何效果。

(2)创建一个显示文字的Button,代码如下:

kotlin 复制代码
@Composable
fun Greeting() {
    Button(onClick = {
        showToast("点击了按钮")
    }) {
        Text(text = "确定")
    }
}

content提供了RowScope的作用域,所以当我们想在文字前面水平摆放一个Icon时,只需要在content中顺序书写即可:

kotlin 复制代码
@Composable
fun Greeting() {
    Button(onClick = {
        showToast("点击了按钮")
    }) {
        Icon(imageVector = Icons.Filled.Done, contentDescription = null)
        Text(text = "确定")
    }
}

UI效果

(3)Button的参数interactionSourceButton有一个参数interactionSource,它是一个可以监听组件状态的事件源,通过它我们可以根据组件状态设置不同的样式,比如按钮按下时什么效果,正常时什么效果,类似传统视图中的SelectorinteractionSource通过以下方法获取当前组件状态:

  • interactionSource.collectIsPressedAsState()判断是否按下状态。
  • interactionSource.collectIsFocusedAsState()判断是否获取焦点的状态。
  • interactionSource.collectIsDraggedAsState()判断是否拖动。

来看下面的例子,通常状态下按钮背景色为灰色,当处于按下状态时,背景色变为黑色:

kotlin 复制代码
@Composable
fun Greeting() {
   val interactionSource = remember { MutableInteractionSource() }
   val pressState = interactionSource.collectIsPressedAsState()
   val backgroundColor = if (pressState.value) Color.Black else Color.Gray
   Button(
       onClick = {},
       interactionSource = interactionSource,
       colors = ButtonDefaults.buttonColors(backgroundColor = backgroundColor)
   ) {
       Text(text = "确定", color = Color.White)
   }
}

UI效果

Jetpack Compose博物馆中有一种写法可以借鉴:

①创建 Data class 来记录不同状态下按钮的样式

kotlin 复制代码
data class ButtonState(var text: String, var textColor: Color, var buttonColor: Color)

②使用 MutableInteractionSource() 获取状态,根据不同状态创建样式,代码如下:

kotlin 复制代码
@Composable
fun Greeting() {
    // 获取按钮的状态
    val interactionState = remember { MutableInteractionSource() }

    // 使用 Kotlin 的解构方法
    val (text, textColor, buttonColor) = when {
        interactionState.collectIsPressedAsState().value  -> ButtonState("Just Pressed", Color.Red, Color.Black)
        else -> ButtonState( "Just Button", Color.White, Color.Red)
    }

    Button(
        onClick = { /*TODO*/ },
        interactionSource = interactionState,
        elevation = null,
        shape = RoundedCornerShape(50),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = buttonColor,      //buttonColor
        ),
        modifier = Modifier.width(IntrinsicSize.Min).height(IntrinsicSize.Min)
    ) {
        Text(
            text = text, color = textColor    //text,textColor
        )
    }
}

二、IconButton图标按钮

上一篇中的IconButton

三、FloatingActionButton(FAB)悬浮按钮

具体参数如下:

kotlin 复制代码
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun FloatingActionButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    shape: Shape = MaterialTheme.shapes.small.copy(CornerSize(percent = 50)),
    backgroundColor: Color = MaterialTheme.colors.secondary,
    contentColor: Color = contentColorFor(backgroundColor),
    elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
    content: @Composable () -> Unit
) {...}

下面是一个简单的例子

kotlin 复制代码
@Composable
fun Greeting() {
    val isClick = remember {
        mutableStateOf(false)
    }
    //修改图标
    val imageVector = if (isClick.value) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder

    FloatingActionButton(
        onClick = { isClick.value = !isClick.value },
        backgroundColor = Color.White,
        contentColor = Color.Red
    ) {
        Icon(imageVector = imageVector, contentDescription = null)
    }
}

UI效果

除了普通的FAB之外,Compose也提供了带有文字扩展的FAB,即ExtendedFloatingActionButton组件,源码如下:

kotlin 复制代码
@Composable
fun ExtendedFloatingActionButton(
    text: @Composable () -> Unit,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    icon: @Composable (() -> Unit)? = null,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    shape: Shape = MaterialTheme.shapes.small.copy(CornerSize(percent = 50)),
    backgroundColor: Color = MaterialTheme.colors.secondary,
    contentColor: Color = contentColorFor(backgroundColor),
    elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation()
) {...}

下面是一个简单的例子:

kotlin 复制代码
@Composable
fun Greeting() {
    ExtendedFloatingActionButton(
        text = { Text(text = "喜欢") },
        onClick = { },
        icon = { Icon(imageVector = Icons.Filled.Favorite, contentDescription = null) },
        contentColor = Color.Red
    )
}

UI效果

参考了以下内容

Jetpack Compose博物馆

实体书 Jetpack Compose从入门到实战

相关推荐
每次的天空14 分钟前
Android-自定义View的实战学习总结
android·学习·kotlin·音视频
恋猫de小郭41 分钟前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
断剑重铸之日2 小时前
Android自定义相机开发(类似OCR扫描相机)
android
随心最为安2 小时前
Android Library Maven 发布完整流程指南
android
岁月玲珑2 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
还鮟6 小时前
CTF Web的数组巧用
android
小蜜蜂嗡嗡7 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
aqi007 小时前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体
zhangphil9 小时前
Android理解onTrimMemory中ComponentCallbacks2的内存警戒水位线值
android
你过来啊你9 小时前
Android View的绘制原理详解
android