0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Composeで自前のCheckBoxを実装する

Posted at

はじめに

ComposeのDefaultではチェックボックスがTrueの時の枠線を設定することができないのでカスタムのチェックボックスを作っていきます

コード

/**
 * カスタムチェックボックス
 *
 * チェック時に白い背景、オレンジの枠線、オレンジのチェックマークを表示します。
 *
 * @param checked チェック状態
 * @param onCheckedChange チェック状態変更時のコールバック
 * @param modifier Modifier
 * @param size チェックボックスのサイズ
 * @param checkedBackgroundColor チェック時の背景色
 * @param checkedBorderColor チェック時の枠線の色
 * @param checkedCheckmarkColor チェック時のチェックマークの色
 * @param uncheckedBackgroundColor 未チェック時の背景色
 * @param uncheckedBorderColor 未チェック時の枠線の色
 * @param borderWidth 枠線の太さ
 * @param cornerRadius 角の丸み
 */
@Composable
fun CustomCheckbox(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier,
    size: Dp = 24.dp,
    checkedBackgroundColor: Color = AppColors.White,
    checkedBorderColor: Color = AppColors.Gray,
    checkedCheckmarkColor: Color = AppColors.Orange,
    uncheckedBackgroundColor: Color = Color.Transparent,
    uncheckedBorderColor: Color = AppColors.Gray,
    borderWidth: Dp = 2.dp,
    cornerRadius: Dp = 4.dp,
) {
    val shape = RoundedCornerShape(cornerRadius)
    val interactionSource = remember { MutableInteractionSource() }

    Box(
        modifier = modifier
            .size(size)
            .clip(shape)
            .background(
                color = if (checked) checkedBackgroundColor else uncheckedBackgroundColor,
                shape = shape
            )
            .border(
                width = borderWidth,
                color = if (checked) checkedBorderColor else uncheckedBorderColor,
                shape = shape
            )
            .clickable(
                interactionSource = interactionSource,
                indication = ripple(bounded = true),
                onClick = { onCheckedChange(!checked) }
            ),
        contentAlignment = Alignment.Center
    ) {
        if (checked) {
            Icon(
                painter = painterResource(R.drawable.ic_check_plan_done),
                contentDescription = null,
                tint = checkedCheckmarkColor,
                modifier = Modifier.size(size * 0.7f)
            )
        }
    }
}

最後に

なんで選択時の枠線が消える仕様なんですかね〜

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?