Android TextView setTextSize Gotcha

Most developers know about the different ways to specify dimensions of visual elements in Android. While setting dimensions for visual elements is usually done in “device independent pixels”, it is recommended to use “scale independent pixels” (sp) for type. The Android OS provides a setting (under the Display category on stock Android) where users can set the default minimun font size of all applications to small, normal, large or huge, an important accessibility feature for users with poor eyesight. Any text fontSize set in sp’s will scale up or down to respect this setting.

That said, you may want your textView to not scale up or down with the settings. Setting the TextView value to some sp value in the layout.xml file will do that. However if you are setting the text size in code, remember that even if you do read the dimensions from a dimen.xml file with values set in dp, the value returned cannot be used in textView.setTextSize (value) since it will interpret those values as sp’s regardless. To set dp values, use the other setTextSize method that takes an additional parameter: how to interpret the numbers being read.

TL;DR: Use setTextSize(TypedValue.COMPLEX_UNIT_DIP, xx) to set dp values to textviews

Author: Arpit Mathur

Arpit Mathur is a Principal Engineer at Comcast Labs where he is currently working on a variety of topics including Machine Learning, Affective Computing, and Blockchain applications. Arpit has also worked extensively on Android and iOS applications, Virtual Reality apps as well as with web technologies like JavaScript, HTML and Ruby on Rails. He also spent a couple of years in the User Experience team as a Creative Technologist.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: