Take the 2-minute tour ×

I'm attempting to build a layout programmatically.

This layout is dynamic. Based on the data read from a database, it could look different every time.

I have a LinearLayout with its orientation set to vertical.

I want to fit as many TextViews with text (the data from database) as I can on a "row".

What I'm doing is building LinearLayouts that are the rows. These LinearLayouts are populated with TextViews. I build the TextView, set the text, and then check the width to see if it will fit on this row (by subtracting the sum of all TextView widths from the screen width and see if the new TextView will fit). If not, I create a new LinearLayout and start adding TextViews to that one.

The problem is myTextView.getWidth() and myTextView.getMeasuredWidth() both return 0.

Why? How can I get the width of the TextView?

share|improve this question
I think, it may be that you are calling getWidth() too early...BTW where you are calling it? Looks like you may be doing in onCreate(), you can try the call in onMeasure() –  TheCottonSilk Feb 5 '11 at 3:49
add comment

1 Answer

Well first of all, please post your code. Second the getWidth/getHeight returning zero question gets asked A LOT so you could search SO for more answers.

Assuming your calling these methods during onCreate (which is probably the case), the UI hasn't been drawn yet so the returned value is zero. You can't get the width or height of the view until it has been drawn.

share|improve this answer
Using an AsyncQueryHandler, I query for the data from the db. The AsyncQueryhandler is called in onResume(). When the Cursor is fetched, I call a method to build the View objects with the data. I've tried immediately adding a newly created TextView to an already-drawn LinearLayout, but getWidth() on the TextView still returns 0. I get that it's 0 because it hasn't been drawn. I just don't know how to get around it (meaning, I don't know how to get the draw code to run so I can grab the width). –  Andrew Feb 5 '11 at 4:14
Did you try onLayout()? : Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their their children. –  TheCottonSilk Feb 5 '11 at 5:02
add comment

Your Answer


