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

Jetpack Compose Text组件报“无匹配可用函数”,改单位为何能解决?

问题原因与解决办法:Jetpack Compose Text组件编译错误

错误原因

你遇到的None of the following functions can be called with the arguments supplied编译错误,核心是Text组件的fontSize参数不接受dp单位:

  • Jetpack Compose里,dp(密度无关像素)是专门用于布局尺寸(比如控件宽高、内边距)的单位,它只适配屏幕密度,不会随系统字体缩放设置改变。
  • 字体大小必须用sp(缩放无关像素),这是Android官方推荐的字体单位,会同时适配屏幕密度和系统的字体缩放偏好,保证不同字体大小设置下的可读性。
  • Text组件的fontSize参数要求的是TextUnit类型,dp属于布局维度的单位类型,和fontSize要求的类型不匹配,因此编译器找不到符合参数要求的重载函数,抛出错误。

正确处理方式

  1. 所有字体大小参数统一替换为sp单位,保留dp用于布局相关属性(比如你的padding(16.dp)是正确的,无需修改)。
  2. 确保导入sp的包:import androidx.compose.ui.unit.sp。

修正后的代码

import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun HeaderText(header: String, modifier: Modifier = Modifier) {
    Text(text = header, fontSize = 24.sp, modifier = modifier.padding(16.dp))
}

@Composable
fun ParaGrph(paragraph: String, modifier: Modifier = Modifier) {
    Text(text = paragraph, fontSize = 16.sp, modifier = modifier.padding(16.dp))
}

@Preview(showBackground = true, showSystemUi = true, name = "new preview")
@Composable
fun SamplePreview() {
    HeaderText(header = stringResource(R.string.Header_text))
    ParaGrph(paragraph = "Hello there")
}

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:12:03