我在Android Studio中通过Empty Compose Activity向导创建了一个新项目.

代码A由Android Studio生成代码.

Text(text = "Hello $name!")用默认字体样式显示文本,我希望得到文本的大小和单位,比如16sp,我在哪里可以找到这些信息?

Code A

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {               
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Greeting("Android")
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Composable
fun MyApplicationTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) {
        DarkColorPalette
    } else {
        LightColorPalette
    }

    MaterialTheme(
        colors = colors,
        typography = Typography,
        shapes = Shapes,
        content = content
    )
}

推荐答案

如果您使用的是默认主题,则它位于

MaterialTheme(
    colorScheme = colorScheme,
    typography = Typography,
    content = content
)

// Set of Material typography styles to start with
val Typography = Typography(
    bodyLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        // HERE
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.5.sp
    )
    /* Other default text styles to override
    titleLarge = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        fontSize = 22.sp,
        lineHeight = 28.sp,
        letterSpacing = 0.sp
    ),
    labelSmall = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Medium,
        fontSize = 11.sp,
        lineHeight = 16.sp,
        letterSpacing = 0.5.sp
    )
    */
)

然而,如果您应用任何其他主题或从另一个库获取文本,则可以使用onTextLayout回调来获取文本的大小,该回调将返回有关文本的大量数据.

如果不移除字体大小顶部或底部的默认填充,将无法在sp中获得正确的高度.您可以使用下面的方法获得sp中的文本高度.我试着用LineHeightStyle Api也需要判断一下line Height是否正确.

Column {
    var heightInPx by remember { mutableStateOf(0f) }
    var info by remember { mutableStateOf("") }
    val heightInSp = LocalDensity.current.run { heightInPx.toSp() }
    Text("Hello World",
        modifier = Modifier
            .border(1.dp, Color.Green)
            .fillMaxWidth(),
        style = TextStyle(
            fontSize = 40.sp,
            platformStyle = PlatformTextStyle(
                includeFontPadding = false
            ),
            lineHeightStyle = LineHeightStyle(
                alignment = LineHeightStyle.Alignment.Top,
                trim = LineHeightStyle.Trim.Both
            )
        ),
        onTextLayout = { result: TextLayoutResult ->
            val cursorRect = result.getCursorRect(0)

            info = "firstBaseline: ${result.firstBaseline}, " +
                    "lastBaseline: ${result.lastBaseline}\n" +
                    "cursorRect: $cursorRect\n" +
                    "getLineBottom: ${result.getLineBottom(0)}, " +
                    "getBoundingBox: ${result.getBoundingBox(0)}"
            heightInPx =
                result.size.height.toFloat()
        }
    )

    Text("Height in px: $heightInPx, height in sp: $heightInSp")
    Text(info)
}

Kotlin相关问答推荐

映射中列表类型的Kotlin可空接收器?

Kotlin Poet 的导入不明确

为什么我的通用Kotlin函数中的这个转换未经判断?

为什么在jacksonObjectMapper上将DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES设置为false无效?

Webpack 配置未应用于 kotlin 多平台react 项目

如果带注释的成员未被特定块包围,则发出 IDE 警告

通过顺序多米诺骨牌操作列表管理对象的最佳方法是什么?

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

Dagger 2 ContributesAndroidInjector 为模块提供活动

禁用 Android 12 默认启动画面

为什么我在使用 Jetpack Compose clickable-Modifier 时收到后端内部错误:Exception during IR lowering error?

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

是否可以在 kotlin 中嵌套数据类?

使用 Kotlin 创建新目录,Mkdir() 不起作用

在 Kotlin 中实现 (/inherit/~extend) 注解

Kotlin - 来自 KType 的 KClass<*>

如何在 Kotlin 中传递有界通配符类型参数?

Kotlin 中的内联构造函数是什么?

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用

Spring R2DBC DatabaseClient.as(…)