Android: Get the size of the Body Layout Dynamically

前端 未结 3 1505
南方客
南方客 2021-01-06 16:10

I want to get the height/width of the Middle(Body) layout in onCreate() method.

My main.xml is :



        
相关标签:
3条回答
  • 2021-01-06 16:52

    I find overriding the following method prevents the width and height being 0. At this stage of the Activity all of the View's in the Activity should be inflated.

    public void onWindowFocusChanged (boolean hasFocus)
    {
         super.onWindowFocusChanged(hasFocus);
         ScrollView scrollView = (ScrollView) findViewById(R.id.svtest);
         int width = scrollView.getWidth();
         int height = scrollView.getHeight();
    }
    
    0 讨论(0)
  • 2021-01-06 16:55

    Firstly, don't get view dimensions in onCreate() since the view might not have been initialized yet. You can do it in the onStart() method. All the views will have been inflated and laid out on the screen at that point:

    @Override
        protected void onStart() {
            super.onStart();
            ScrollView scrollView = (ScrollView) findViewById(R.id.svtest);
            int width = scrollView.getWidth();
            int height = scrollView.getHeight();
        }
    
    0 讨论(0)
  • 2021-01-06 16:56

    Added: This applies for all types of layout. Not only ScrollView.

    getWidth() and getHeight() methods returns 0 when layouts width and height are set as match_parent and wrap_content. dimensions are not measured.

    The right methods to use to get measured dimensions are getMeasuredWidth() and getMeasuredHeight().

    Note: measured dimensions in onCreate method are not initialized yet.

    The correct way and place is (snippet can be added anywhere including onCreate):

    ScrollView scrollView = (ScrollView)findViewById(R.id.svtest);
    ViewTreeObserver vto = scrollView.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            if (Build.VERSION.SDK_INT < 16)
                scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
            else
                scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    
            int width  = scrollView.getMeasuredWidth();
            int height = scrollView.getMeasuredHeight(); 
    
            // postpone any calculation depend on it to here.
            // regardless what it is. UI or http connection.
        } 
    });
    

    Some answers tried to do it onStart() method. but, they tried to call getWidth() and getHeight() methods. Try getMeasuredWidth() and getMeasuredHeight(). it works without adding OnGlobalLayoutListener. The listener is only required if you want to get the dimensions in the on create method. in any later stage the listener is not required because by then the dimensions will be measured(on start for example).

    0 讨论(0)
提交回复
热议问题