When doing Android development, sometimes you need to measure the width and height of a control, and there are three common ways to do this:
(1) Override the onWindowFocusChanged(hasFocus: Boolean) method to get the width and height of the control within this method.
This method is called when the focus of the Activity's window changes, which can be divided into when the window gains focus and when the window loses focus.When the Activity's focus changes, the relevant view hierarchy has been measured, laid out and drawn.
- Gain focus: when the Activity's window returns to the foreground from the background, or resumes from another window. When gaining focus, hasFocus is passed true.
- Loss of focus: when the Activity's window is covered by another window, or the user presses the home button to put the application into the background. When focus is lost, hasFocus is passed false.
(2) Call the View's post(Runnable action) method and get the width and height of the control in the run method.
The View's drawing process consists of onMesure (which measures the width and height of the control), onLayout (which lays it out), and onDraw (which draws it). the post method ensures that the passed Runnable object will be run after the measurement, layout, and drawing of the view tree has been completed, so the test can get the width and height of the control.
(3) Observer pattern, add a listener to ViewTreeObserver, and get the width and height of the control in the overridden method onGlobalLayout().
ViewTreeObserver is a class that listens to the overall changes of the view tree and observes various global events of the view tree. With ViewTreeObserver, we can get the width and height information of the control after the layout process of the view tree is completed.
class MainActivity : AppCompatActivity() { private lateinit var tv: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(.activity_main) tv=findViewById() (object:Runnable{//The first way override fun run() { val width= val height= ("post","width=${width},height=${height}") } }) (object:{//The second way override fun onGlobalLayout() { val width= val height= ("viewTreeObserver","width=${width},height=${height}") } }) } override fun onWindowFocusChanged(hasFocus: Boolean) {//The third way super.onWindowFocusChanged(hasFocus) val width= val height= ("onWindowFocusChanged","width=${width},height=${height}") } }