Android: Need to use onSizeChanged for View.getWidth/Height() in class extending Activity

后端 未结 5 2061
渐次进展
渐次进展 2020-12-15 20:15

I want to use getWidth()/getHeight() to get width/height of my XML-Layout. I read I have to do it in the method onSizeChanged() otherwise I will get 0 ( Android: Get the scr

5条回答
  •  有刺的猬
    2020-12-15 21:10

    You dont have to create a customView to get its height and width. You can add an OnLayoutChangedListener (description here) to the view whose width/height you want, and then essentially get the values in the onLayoutChanged method, like so

    View myView = findViewById(R.id.my_view);
    myView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
    
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
                    int oldBottom) {
                // its possible that the layout is not complete in which case
                // we will get all zero values for the positions, so ignore the event
                if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                    return;
                }
    
               // Do what you need to do with the height/width since they are now set
            }
        });
    

    The reason for this is because views are drawn only after the layout is complete. The system then walks down the view heirarchy tree to measure the width/height of each view before drawing them.

提交回复
热议问题