You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:46:37