Android Compose中Tab的text与icon参数调用可组合函数报错求助
解决Compose Material3 Tab组件text/icon参数报错问题
问题原因
你错误地同时使用了Tab的text/icon参数和content lambda(即Tab末尾的空{}),触发了不支持text/icon参数的Tab重载函数,导致text/icon中的Composable组件(Text、Icon)无法在正确的上下文执行,出现@Composable invocations can only happen from the context of a @Composable function报错。
解决方案
方案1:使用带text/icon参数的Tab重载
删除Tab组件末尾的空lambda{},同时确保selectedTabIndex是可观察的状态变量(用mutableStateOf声明),代码示例:
val selectedTabIndex = remember { mutableStateOf(0) } PrimaryTabRow( selectedTabIndex = selectedTabIndex.value ) { tabItems.forEachIndexed { index, item -> Tab( selected = (selectedTabIndex.value == index), onClick = { selectedTabIndex.value = index }, text = { Text(text = item.titulo) }, icon = { Icon( imageVector = if (index == selectedTabIndex.value) item.selecIcon else item.unselecIcon, contentDescription = item.titulo ) } ) } }
方案2:自定义Tab内容(更灵活)
如果需要调整图标和文本的布局(比如间距、排列方向),可以放弃text和icon参数,直接在Tab的content lambda中组合组件:
val selectedTabIndex = remember { mutableStateOf(0) } PrimaryTabRow( selectedTabIndex = selectedTabIndex.value ) { tabItems.forEachIndexed { index, item -> Tab( selected = (selectedTabIndex.value == index), onClick = { selectedTabIndex.value = index } ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.padding(16.dp) ) { Icon( imageVector = if (index == selectedTabIndex.value) item.selecIcon else item.unselecIcon, contentDescription = item.titulo ) Spacer(modifier = Modifier.height(4.dp)) Text(text = item.titulo) } } } }
内容的提问来源于stack exchange,提问作者Ziki Rach
相关产品推荐
相关产品推荐

