Skip to main content

Are you calling getWidth()getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers developers is to use the width and heightand height of a view inside its constructor constructor. When a view’s constructor is called, Android doesn’t know know yet how big the view will be be, so the the sizes are set to zero. The real sizes are sizes are calculated during the layoutthe layout stage, which occurs after construction construction but before anything is drawnis drawn. You can use the onSizeChanged( )methodonSizeChanged() method to be notified of the values whenthe values when they areare known, or you can use the getWidth( the )getWidth() and getHeight( )methods latergetHeight() methods later, such as in the onDraw( )onDraw() method.

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged( )method to be notified of the values when they are known, or you can use the getWidth( ) and getHeight( )methods later, such as in the onDraw( ) method.

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

Source Link
Mark B
  • 203.2k
  • 27
  • 339
  • 332

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged( )method to be notified of the values when they are known, or you can use the getWidth( ) and getHeight( )methods later, such as in the onDraw( ) method.