Determining the size of an Android view at runtime

前端 未结 12 1928
陌清茗
陌清茗 2020-11-22 09:59

I am trying to apply an animation to a view in my Android app after my activity is created. To do this, I need to determine the current size of the view, and then set up an

12条回答
  •  没有蜡笔的小新
    2020-11-22 10:30

    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.

提交回复
热议问题