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 Software Engineer at Comcast Labs where he is currently working on Virtual and Augmented Reality as well as investigating Blockchains and the decentralized internet.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s