使用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
感谢阅读