In Android, can a StaticLayout with Spans be Align.CENTER'ed?

217 Views Asked by At

I am trying to center CharSequences with Spans using StaticLayout. Everything works fine when textPaint.textAlign = Paint.Align.LEFT.

working with LEFT alignment

However, if I set textPaint.textAlign = Paint.Align.CENTER, everything gets wonky.

wonky with CENTER alignment

It looks as if the spanned portions are stripped out, then the "centering calc" is done, then the text is rendered.

In my code, the alignment is changed via 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)
        }
    }

One final point:

Changing

            canvas.withTranslation(xPos, yPos) {
                staticLayout.draw(canvas)
            }

to simply

            staticLayout.draw(canvas)

moves the output to the upper left, but it's just as wonky.

I've researched this and cannot find anything on point. Not here at SO, nor elsewhere on the web. I did find a couple of things talking about this same type of issue with CSS where the conclusion seemed to be "can't be done".

Am I missing something simple here? Or is there a more complex approach I need to take? Or is this not possible?

note: minSdk is 23 (M / Marshmallow)

1

There are 1 best solutions below

0
Free Dorfman On

I figured out my mistake. Decided to post for anyone who may encounter this issue.

Don't use

    textPaint.textAlign = Paint.Align.CENTER

set the alignment in the StaticLayout.Builder

    val staticLayout = StaticLayout.Builder
        .obtain(cs, 0, cs.length, textPaint, wid)
        .setAlignment(Layout.Alignment.ALIGN_CENTER)
        .build()