Skip to content

Instantly share code, notes, and snippets.

@ed-george
Created September 8, 2025 23:12
Show Gist options
  • Select an option

  • Save ed-george/4104855f66d9e2ba720006c2ca7eedd1 to your computer and use it in GitHub Desktop.

Select an option

Save ed-george/4104855f66d9e2ba720006c2ca7eedd1 to your computer and use it in GitHub Desktop.
VerticalTextView XML / View implementation for androidx.text.vertical 1.0.0-alpha01
package dev.spght.example.text
import android.content.Context
import android.graphics.Canvas
import android.text.Spanned
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import androidx.text.vertical.VerticalTextLayout
open class VerticalTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {
private var textLayout: VerticalTextLayout? = null
private var pendingText: Spanned? = null
private var pendingPaint: TextPaint? = null
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val text = pendingText ?: return
val paint = pendingPaint ?: return
textLayout = generateLayout(
text = text,
paint = paint,
height = h.toFloat()
)
}
override fun onDraw(canvas: Canvas) {
textLayout?.draw(canvas, width.toFloat(), 0.0f)
}
fun setText(text: Spanned, paint: TextPaint) {
pendingText = text
pendingPaint = paint
requestLayout()
}
private fun generateLayout(
text: Spanned,
paint: TextPaint,
height: Float,
) = VerticalTextLayout.Builder(
text = text,
start = 0,
end = text.length,
paint = paint,
height = height,
).build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment