自定义滑块选择器

效果图

使用Composable自定义的滑动选择器

/**
 * 滑动选择器
 * @param contentList 内容
 * @param defaultSelect 默认选中项
 */
@Composable
fun MSelect(
    contentList: List<String>,
    defaultSelect: Int = 0,
    marginStart: Dp = 0.dp,
    marginTop: Dp = 0.dp,
    marginEnd: Dp = 0.dp,
    marginBottom: Dp = 0.dp,
    selectCallback: (Int) -> Unit,
) {
    val count = contentList.size
    Box(
        modifier = Modifier
            .padding(marginStart, marginTop, marginEnd, marginBottom)
            .size(54.dp * count, 32.dp)
            .background(Color(0XFFF0F2F5), RoundedCornerShape(8.dp))
            .clip(RoundedCornerShape(8.dp)),
        contentAlignment = Alignment.CenterStart
    ) {
        val selectIndex = remember { mutableStateOf(defaultSelect) }
        val slideWidth = 54.dp
        val selectAnima = animateFloatAsState(targetValue = selectIndex.value.toFloat())
        Divider(
            modifier = Modifier
                .padding(start = (slideWidth * selectAnima.value))
                .size(slideWidth, 32.dp)
                .padding(2.dp)
                .clip(RoundedCornerShape(8.dp)),
            color = Color.White
        )
        Row(
            modifier = Modifier
                .fillMaxSize(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceAround
        ) {
            contentList.forEachIndexed { index, s ->
                Text(
                    text = s,
                    color = colorResource(id = R.color.color_23262b),
                    fontWeight = if (index == selectIndex.value) FontWeight.Bold else null,
                    modifier = Modifier.clickable {
                        selectIndex.value = index
                        selectCallback.invoke(index)
                    }
                )
            }
        }
    }
}

为了在方便在不是Composable布局的地方调用, 添加

class MSelectView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    private val contentList: List<String> = mutableListOf(),
    private val selectCallback: (Int) -> Unit = {},
    private val defaultSelect: Int = 0,
) : FrameLayout(context, attrs) {
    init {
        addView(ComposeView(context).apply {
            addToLifecycle()
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                MSelect(contentList = contentList, selectCallback = selectCallback, defaultSelect = defaultSelect)
            }
        })
    }
}

虽然在xml可以使用<androidx.compose.ui.platform.ComposeView>
但我总觉得在java代码中调用不方便

#end
感谢阅读

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值