Relative Layout get Width/Height return 0

前端 未结 2 709
礼貌的吻别
礼貌的吻别 2020-12-11 06:51

I need to get width and height of Relative layout, however I do not know when the Relative Layout is ready to provide me these two attributes. My activity has several tabs a

相关标签:
2条回答
  • 2020-12-11 07:48

    addOnGlobalLayoutListener is deprecated use removeOnGlobalLayoutListener .For better handling extending the solution provided above by @fasteque

        YOUR_LAYOUT_INSTANCE.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                // gets called after layout has been done but before display.
                if (Build.VERSION.SDK_INT < 16) {
    
                            YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } 
                else {
                            YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
    
            // get width and height
            }
        });
    
    0 讨论(0)
  • 2020-12-11 07:49

    My suggestion is to use a global layout listener like this in onCreateView:

    YOUR_LAYOUT_INSTANCE = view.findViewById(R.id.YOUR_LAYOUT_ID);
    

    ...

    YOUR_LAYOUT_INSTANCE.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
    {
        @Override
        public void onGlobalLayout()
        {
            // gets called after layout has been done but before display.
            if (Build.VERSION.SDK_INT < 16) {
                YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            // get width and height
        }
    });
    
    0 讨论(0)
提交回复
热议问题