Android UI: Vertical Text View

Bigyan Thapa
2 min readMar 10, 2021

--

In Android app development career, it is more than likely to come across some UI design for which there is no native API or component. One of such requirement is to build a vertical text view. Recently I came across a similar requirement and decided to write a short article. Here, I had to put a label on y-axis of a graph which wasn’t easy since there is no Vertical TextView by default in Android UI framework. So, I did some study and put together this solution. I expect basic understanding of Kotlin along with some understanding of building custom UI components in Android for the readers to understand this article.

We will start off with creating a custom TextView extending android’s TextView class, call it VerticalTextView. The key to the vertical text view is the rotation. Inside the custom class, we define a constant 270f or 90f depending on how you want the text to be read which is the rotation angle. We also keep reference of the measured height and width of the text view by overriding onMeasure function. The actual rotation is done by overriding onDraw function. Inside onDraw, we have to save the canvas being drawn, then translate the canvas to our measured width and height. Now rotate this canvas at 270f angle to make it vertical. We can also rotate it 90f depending on how we want the vertical view.
Then get reference to the text being displayed in the textview, and draw the text on the vertical canvas in the x and y coordinates with the text bounds. Now all is left is to restore the canvas. There are also other ways to get similar behavior like, using new line operator \n , android:rotation="-90" etc. but this is the one worked for my requirements. Please comment if there are better alternatives to this solution.

Summarized steps of the implementation:
* OverrideAppCompatTextView and create a custom TextView.
* Inside onMeasure(..) function, initialize the values for _measuredHeight and _measuredWidth.
* Inside onDraw(..) function:
-> save canvas
-> translate canvas to the _measuredWidth and _measuredHeight
-> rotate canvas 270 degrees, makes the view vertical.
-> get reference to paint and set bounds of the paint to be the same of the current text view.
-> now use drawText() function of canvas to draw the TextView.
-> getViewText() function just returns current text strings set for the TextView.

Please comment or reach out in twitter: @bigyan4424 for questions. Thank you for reading :)

--

--

Bigyan Thapa
Bigyan Thapa

Written by Bigyan Thapa

Senior Mobile Engineer @ Sprout Social, Android Dev, Chicago, USA

No responses yet