Quick android tip, with ems (setEms())

Android | Saturday April 13 2013 14:26 | Comments (0)

I recently ran into an issue with my TextView not wrapping text. For some reason, if the line was too long, it would continue off screen.
I tried many different fixes from across the web, but none worked. I thnk the main problem was that I was not using a defined layout in XML, but rather creating the textview dynamically upon encountering an error.

The answer that I finally settled on was the use of em’s (http://en.wikipedia.org/wiki/Em_(typography)). This type or measurement relates to font sizes, and in Android, helps keep fonts and other objects the same relative sizes across any screen size or resolution.
Loosely speaking, a typical screen width in ems, is equivalent to (the screen width / 24). Going back to my original problem, where I had the text go off the screen, I could use this calculation to set a max width of the text view, and manually make it wrap the text.

Since I also target older versions of android, eg 1.6 and 2.2, I had to use an older deprecated method to get he screen width. If you only target newer versionm eg API 17+, you can use the DisplayManager, but if like me, you want to have maximum compatibility, then you can use the following code to set the width of a layout to be equal to the screen size of whatever device you’re on:.

Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
TextView tvError = new TextView(this);
tvError.setEms(width/24);

Android does come with some built in functions to help text wrap, but from some discussions online, I saw that certain themes, eg Holo, can cause issues like what I’ve experienced. This fix only came about because I didn’t want to change from the Holo Theme.

I hope this helps someone.

EDIT:
Since the above method uses deprecated methods to get the width, I think its best to update this post with the current recommended methods of getting both the width, and the height of a screen in Android:


final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;

No Comments »

No comments yet.

RSS feed. TrackBack URI

Leave a comment