我有一个带有lambda的Composable
函数,用于获取按钮单击操作。我想预览一下这个Composable
函数。但是,可组合函数在添加@Preview
注释后,在@Composable
上添加了这样的lambda错误。
Composable functions with non-default parameters are not supported in Preview unless they are annotated with @PreviewParameter.
可组合函数看起来像
@Composable
fun MyView(onViewButtonClick: () -> Unit) {
Button(
enabled = isEnabled, colors = ButtonDefaults.buttonColors(
backgroundColor = greenColor
),
shape = Shapes.large, onClick = (onViewButtonClick),
modifier = Modifier
.fillMaxWidth()
.padding(15.dp, 40.dp, 15.dp, 15.dp)
) {
Text(
text = stringResource(id = R.string.send_otp),
color = Color.White,
fontSize = 20.sp
)
}
}
它的应用程序类似于
MyView(onViewButtonClick = {
Log.d("ViewButtonClick","ViewButtonClick")
}).
如何使用Lambda查看这个可组合函数的预览?
发布于 2022-02-18 05:53:43
要么为您的可组合提供默认的lambda,要么在预览中实现一个空lambda。
@Composable
fun MyView(onViewButtonClick: () -> Unit = {}) {
Button(
enabled = isEnabled, colors = ButtonDefaults.buttonColors(
backgroundColor = greenColor
),
shape = Shapes.large, onClick = (onViewButtonClick),
modifier = Modifier
.fillMaxWidth()
.padding(15.dp, 40.dp, 15.dp, 15.dp)
) {
Text(
text = stringResource(id = R.string.send_otp),
color = Color.White,
fontSize = 20.sp
)
}
}
@Preview
@Composable
fun MyViewPreview() {
MyView()
}
或
@Composable
fun MyView(onViewButtonClick: () -> Unit) {
Button(
enabled = isEnabled, colors = ButtonDefaults.buttonColors(
backgroundColor = greenColor
),
shape = Shapes.large, onClick = (onViewButtonClick),
modifier = Modifier
.fillMaxWidth()
.padding(15.dp, 40.dp, 15.dp, 15.dp)
) {
Text(
text = stringResource(id = R.string.send_otp),
color = Color.White,
fontSize = 20.sp
)
}
}
@Preview
@Composable
fun MyViewPreview() {
MyView(onViewButtonClick = {})
}
发布于 2022-06-13 04:00:29
如此处所定义的问题,不支持具有非默认参数的可组合函数。这意味着应该在Composable函数中定义默认值,或者如果使用自定义模型,则使用PreviewParameter.
@Preview(showBackground = true)
@Composable
fun Greeting(name: String = "Bharat") {
Surface(modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()) {
Text(text = "Hello $name!")
}
}
@Preview
@Composable
fun UserProfilePreview(
@PreviewParameter(UserPreviewParameterProvider::class) user: User)
{
UserProfile(user)
}
https://stackoverflow.com/questions/71174154
复制相似问题