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

Android中带Span的StaticLayout能否设置Align.CENTER对齐?

问题:StaticLayout带Span文本居中对齐异常

我尝试使用StaticLayout对带有Span的CharSequence进行居中对齐。当设置textPaint.textAlign = Paint.Align.LEFT时,一切正常。但设置为Paint.Align.CENTER后,显示出现异常,看起来像是Span部分被剥离,先计算居中再渲染文本。

我的代码通过doCenter变量控制对齐方式:

override fun onDraw(canvas: Canvas) {
    //:

    val doCenter = true
    val textWidPct = 0.90F
    dpToUse = 10
    val cs = clueDisplayText

    val xPos: Float
    if (doCenter) {
        xPos = clueTextRect.exactCenterX()
        textPaint.textAlign = Paint.Align.CENTER
    } else {
        xPos = clueTextRect.width() * ((1 - textWidPct) / 2)
        textPaint.textAlign = Paint.Align.LEFT
    }
    textPaint.typeface = k.typefaceNormal
    textPaint.textSize = j.dpToPx(dpToUse).toFloat()
    textPaint.color = cc.Black

    val wid = (width * textWidPct).round()
    val staticLayout = StaticLayout.Builder
        .obtain(cs, 0, cs.length, textPaint, wid)
        .build()

    val yPos = clueTextY + j.dpToPx(dpToUse)
    canvas.withTranslation(xPos, yPos) {
        staticLayout.draw(canvas)
    }
}

补充说明:将画布平移的代码改为直接调用staticLayout.draw(canvas)后,文本移到左上角,但显示仍然异常。我在技术社区未找到相关解决方案,类似CSS问题结论是无法实现。请问我是否遗漏了简单的解决方法,或是需要复杂实现,还是该需求本身无法完成?

注:最低兼容SDK版本为23(Marshmallow)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:50:37