阅读 1593

Jetpack Compose Button,IconButton等各种Button的讲解

今天我们会讲解下Button,IconButton, ExtendedFloatingActionButton, FloatingActionButton, IconToggleButton,OutlinedButton,RadioButton,TextButton。这几个Button的用法详解。

一:Button的用法

先来看看Button的源码(OutlinedButton跟Button的属性一样只是两个按钮的形状不太一样)

@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
) {
   ...
}
复制代码
  • content 是表示Button的内容。比如里面可以是一个Text
  • onClick点击的回调
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               }
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • modifier 修饰符 可以参考文章Modifier用法详解
  • enabled 是否可以 (不可用默认是灰色,可用默认是蓝色)
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               },
              modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
              enabled = true
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • border 边框,BorderStroke(width,color)可以设置边框的颜色跟线的宽度。第一个参数width是边框线的宽度,color是边框线的颜色
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               },
              modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
              enabled = true,
              border = BorderStroke(1.dp,color = Color.Black)
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • interactionSource 可以处理状态的,比如按下的时候什么效果,正常时候什么效果。类似之前再布局文件里写Selector。 比如我们下面的例子中设置,如果是选中时候边框线的颜色是绿色,没有选中时候是黑色。 interactionSource.collectIsPressedAsState() 判断是否按下状态interactionSource.collectIsFocusedAsState() 判断是否获取焦点的状态interactionSource.collectIsDraggedAsState() 判断是否拖动
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      val interactionSource = remember {
          MutableInteractionSource()
      }
      val pressState = interactionSource.collectIsPressedAsState()
      val borderColor = if (pressState.value) Color.Green else Color.Black
      
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               },
              modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
              enabled = true,
              border = BorderStroke(1.dp,color = borderColor),
              interactionSource = interactionSource
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • shape 形状 比如我们可以设置RoundedCornerShape(20)圆角20dp
  • elevation 阴影ButtonDefaults.elevation(defaultElevation,pressedElevation,disabledElevation)三个属性值,第一个defaultElevation表示默认的阴影,pressedElevation表示按下时的阴影,disabledElevation表示未启用时候的阴影。
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      val interactionSource = remember {
          MutableInteractionSource()
      }
      val pressState = interactionSource.collectIsPressedAsState()
      val borderColor = if (pressState.value) Color.Green else Color.Black
      
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               },
              modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
              enabled = true,
              border = BorderStroke(1.dp,color = borderColor),
              interactionSource = interactionSource,
              shape = RoundedCornerShape(20),
              elevation = ButtonDefaults.elevation(2.dp,8.dp,0.dp)
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • colors 通过ButtonDefaults.buttonColors(backgroundColor,contentColor,disabledBackgroundColor,disabledContentColor)设置颜色。第一个参数backgroundColor表示设置背景颜色,第二个参数contentColor表示设置内容颜色这里比如说是登录文本的颜色。第三个参数disabledBackgroundColor表示enable等于false的时候的背景颜色,第四个参数disabledContentColor表示enable等于false时候的内容的颜色。
    @Preview()
    @Composable
    fun buttonTest(){
      val context = LocalContext.current
      val interactionSource = remember {
          MutableInteractionSource()
      }
      val pressState = interactionSource.collectIsPressedAsState()
      val borderColor = if (pressState.value) Color.Green else Color.Black
      
      Column(modifier = Modifier.padding(10.dp,10.dp)) {
          Button(
              onClick = {
                  Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
               },
              modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
              enabled = true,
              border = BorderStroke(1.dp,color = borderColor),
              interactionSource = interactionSource,
              elevation = ButtonDefaults.elevation(2.dp,8.dp,0.dp),
              shape = RoundedCornerShape(20),
              colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red,contentColor = Color.Yellow,disabledBackgroundColor = Color.DarkGray,disabledContentColor = Color.Black)
          ){
              Text(text = stringResource(id = R.string.login))
          }
      }
    }
    复制代码
  • contentPadding 通过 PaddingValues()去设置。默认是ButtonDefaults.ContentPadding。表示内容的内边距。 PaddingValues有如下几个方法
    • PaddingValues(all) all表示上下左右都用该边距
    • PaddingValues(horizontal: Dp, vertical: Dp)
    • PaddingValues( start: Dp = 0.dp, top: Dp = 0.dp, end: Dp = 0.dp, bottom: Dp = 0.dp)
    @Preview()
    @Composable
    fun buttonTest(){
     val context = LocalContext.current
     val interactionSource = remember {
         MutableInteractionSource()
     }
     val pressState = interactionSource.collectIsPressedAsState()
     val borderColor = if (pressState.value) Color.Green else Color.Black
     
     Column(modifier = Modifier.padding(10.dp,10.dp)) {
         Button(
             onClick = {
                 Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
              },
             modifier= Modifier.size(80.dp, 40.dp).clip(RoundedCornerShape(20.dp)),
             enabled = true,
             border = BorderStroke(1.dp,color = borderColor),
             interactionSource = interactionSource,
             elevation = ButtonDefaults.elevation(2.dp,8.dp,0.dp),
             shape = RoundedCornerShape(20),
             colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red,contentColor = Color.Yellow,disabledBackgroundColor = Color.DarkGray,disabledContentColor = Color.Black),
             contentPadding = ButtonDefaults.ContentPadding
             // 或者是contentPadding = PaddingValues(4.dp)
         ){
             Text(text = stringResource(id = R.string.login))
         }
     }
    }
    复制代码

二:IconButton的用法

IconButton的构造方法如下

@Composable
fun IconButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable () -> Unit
){
   ...
}
复制代码
  • onClick 点击回调
  • modifier 修饰符
  • enabled 是否可用
  • content 该控件包含的内容
  • interactionSource 跟Button一样,可以根据不同状态去处理一些逻辑。比如按下时候如何,没有按下时候如何。

如下举例。比如IconButton是一个左边是+的icon,右边是文本的控件。该文本如果按下时候是显示减少,不按下显示添加。

@Preview()
@Composable
fun iconButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    val pressText = if(pressState.value) "减少" else "添加"
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
        IconButton(
            onClick = {
              Toast.makeText(context,"点击了添加",Toast.LENGTH_SHORT).show()
            },
            modifier = Modifier.size(80.dp,40.dp).clip(RoundedCornerShape(20)),
            enabled = true,
            interactionSource = interactionSource
            ){
             Row(verticalAlignment=Alignment.CenterVertically) {
               Icon(imageVector = Icons.Filled.Add, contentDescription = "添加的按钮",tint = Color.Red)
               Text(text = pressText,fontSize = 8.sp)
             }
        }
    }
}
复制代码

三:FloatingActionButton和ExtendedFloatingActionButton的用法

FloatingActionButton是Material风格的控件,默认是浮动在右下角的圆形控件。FloatingActionButton的构造函数方法如下:

@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
){
    ...
}
复制代码
  • onClick 点击回调
  • modifier 修饰符
  • interactionSource 跟上面一样,处理不同状态的
  • shape 形状
  • backgroundColor 背景颜色
  • contentColor内容颜色
  • elevation阴影
  • content 内容控件(其实ExtendedFloatingActionButton就是在该内容里添加了一个Row,Row里放了个文本跟Icon)
@Preview()
@Composable
fun floatingActionButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    val pressText = if(pressState.value) "减少" else "添加"
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
       FloatingActionButton(
            onClick = {
              Toast.makeText(context,"点击了按钮",Toast.LENGTH_SHORT).show()
            },
            modifier = Modifier.size(80.dp),
            interactionSource = interactionSource,
            shape = RoundedCornerShape(25.dp),
            backgroundColor = Color.Green,
            contentColor = Color.Blue,
            elevation = FloatingActionButtonDefaults.elevation(defaultElevation=8.dp,pressedElevation = 10.dp)
        ){
            Row(verticalAlignment=Alignment.CenterVertically) {
                Icon(imageVector = Icons.Filled.Add, contentDescription = "Add",tint = Color.Red)
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = "按钮",fontSize =12.sp,color = Color.White)
            }
        }
}
复制代码

ExtendedFloatingActionButton是FloatingActionButton的扩展 ExtendedFloatingActionButton的构造方法如下

@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()
) {
    ...
}
复制代码
  • text显示的文本控件
  • onClick 点击回调
  • modifier 修饰符
  • icon 显示的icon控件
  • interactionSource 跟上面一样,处理不同状态的
  • shape 形状
  • backgroundColor 背景颜色
  • contentColor内容颜色
  • elevation阴影 通过FloatingActionButtonDefaults.elevation(defaultElevation,pressedElevation)设置,第一个参数是默认阴影,第二个是按下时候的阴影
@Preview()
@Composable
fun extendedFloatingActionButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    val pressText = if(pressState.value) "减少" else "添加"
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
        ExtendedFloatingActionButton(text = { Text(text = pressText,fontSize =12.sp,color = Color.White)},onClick = {
            Toast.makeText(context,"点击了按钮",Toast.LENGTH_SHORT).show()
        },
//            modifier = Modifier.size(50.dp),
            icon ={
              Icon(imageVector = Icons.Filled.Add, contentDescription = "Add",tint = Color.Red)
            },
            interactionSource = interactionSource,
            shape = RoundedCornerShape(25.dp),
            backgroundColor = Color.Green,
            contentColor = Color.Blue,
            elevation = FloatingActionButtonDefaults.elevation(defaultElevation=8.dp,pressedElevation = 10.dp))
    }
}
复制代码

四:IconToggleButton的用法

IconToggleButton是属于那种用于点赞,收藏的那种Icon可以改变状态的控件。代码如下:

@Composable
fun IconToggleButton(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable () -> Unit
) {
   ...
}
复制代码
  • checked 是否选中的状态
  • onCheckedChange 是否选中状态变化的监听
  • modifier 修饰符
  • enabled 是否可用
  • interactionSource 跟上面Button解释一致
  • content 控件内容

比如我们举个例子,在点赞按下或者选中的时候,用红色的点赞,否则用黑色的点赞图标

@Preview()
@Composable
fun iconToggleButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    var isCheck = remember {
        mutableStateOf(false)
    }
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
         IconToggleButton(
            checked = isCheck.value,
            onCheckedChange = {
             isCheck.value = it
            },
            modifier = Modifier.size(50.dp),
            enabled = true,
            interactionSource = interactionSource
        ){
               Icon(imageVector = Icons.Filled.Favorite, contentDescription = "点赞图标",tint = if(isCheck.value || pressState.value) Color.Red else Color.Black)
        }
    }
}
复制代码

五:RadioButton的用法

RadioButton是单选按钮,RadioButton的代码如下

@Composable
fun RadioButton(
    selected: Boolean,
    onClick: (() -> Unit)?,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    colors: RadioButtonColors = RadioButtonDefaults.colors()
){
    ...
}
复制代码
  • selected 是否选中
  • onClick 点击回调
  • modifier 修饰符
  • enabled 是否可用
  • interactionSource 跟上面Button解释一致
  • colors 设置颜色 RadioButtonDefaults.colors(selectedColor, unselectedColor,disabledColor)方法有三个参数,第一个selectedColor表示选中时候的颜色,第二个参数unselectedColor表示没有选中时候的颜色,第三个disabledColor表示不可用时候的颜色。
@Preview()
@Composable
fun iconToggleButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    var isCheck = remember {
        mutableStateOf(false)
    }
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
          RadioButton(
          selected = isCheck.value,
          onClick = {
            isCheck.value = !isCheck.value
          },
          modifier = Modifier.size(50.dp),
          enabled = true,
          interactionSource = interactionSource,
          colors = RadioButtonDefaults.colors(selectedColor = Color.Red,unselectedColor = Color.Black,disabledColor = Color.Gray))
    }
}
复制代码

六:TextButton的用法

TextButton文本按钮,来看看TextButton的代码,其实TextButton就是new了Button。

@Composable
fun TextButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    elevation: ButtonElevation? = null,
    shape: Shape = MaterialTheme.shapes.small,
    border: BorderStroke? = null,
    colors: ButtonColors = ButtonDefaults.textButtonColors(),
    contentPadding: PaddingValues = ButtonDefaults.TextButtonContentPadding,
    content: @Composable RowScope.() -> Unit
) = Button(
    onClick = onClick,
    modifier = modifier,
    enabled = enabled,
    interactionSource = interactionSource,
    elevation = elevation,
    shape = shape,
    border = border,
    colors = colors,
    contentPadding = contentPadding,
    content = content
)
复制代码
  • onClick 点击事件
  • modifier 修饰符
  • enabled 是否可用
  • interactionSource 跟Button一致
  • elevation 阴影
  • shape 形状设置
  • border 边框设置
  • colors 颜色设置
  • contentPadding 内容边距的设置
  • content 包含的控件
@Preview()
@Composable
fun textButtonTest(){
    val context = LocalContext.current
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val pressState = interactionSource.collectIsPressedAsState()
    Column(modifier = Modifier.padding(10.dp,10.dp)) {
         TextButton(
            onClick = {
                Toast.makeText(context,"点击了登录",Toast.LENGTH_SHORT).show()
            },
            modifier = Modifier
                .size(80.dp, 40.dp)
                .clip(RoundedCornerShape(20)),
            enabled = true,
            interactionSource = interactionSource,
            elevation = ButtonDefaults.elevation(2.dp,8.dp,0.dp),
            shape = RoundedCornerShape(20),
            border = BorderStroke(1.dp, if(pressState.value) Color.Red else Color.Yellow),
            colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue,contentColor = Color.White,disabledBackgroundColor = Color.Gray,disabledContentColor = Color.Black),
            contentPadding = ButtonDefaults.ContentPadding) {
                Text(text = stringResource(id = R.string.login),fontSize = 14.sp)
        }
    }
}
复制代码
文章分类
Android