As suggested in this stackoverflow thread, I am using ViewTreeObserver to wait for first layout so that I can then measure width and height of my tablelayout (that is the only element in my xml, width and height are set to match parent). However, I am getting only 0. (The code is placed inside a method which is called immediately after setContentView in OnCreate)
My whole aim of trying to use getMeasuredWidth/getMeasuredHeight is to avoid using metrics method (as there are overheads to determine height of status bar, navigation bar, etc)
mysquare = (TableLayout) findViewById(R.id.square);
ViewTreeObserver viewTreeObserver = mysquare.getViewTreeObserver();
if (viewTreeObserver.isAlive())
{
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
if(Build.VERSION.SDK_INT >= 16)
mysquare.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
mysquare.getViewTreeObserver().removeGlobalOnLayoutListener(this);
screen_width = mysquare.getMeasuredWidth();
screen_height = mysquare.getMeasuredHeight();
}
});
}
If I use a delayed execution approach as given below (getMeasuredWidth/getMeasuredHeight are used inside gameSelectionLayout), then I get correct values, provided the delay value is appropriate for particular device. This could easily lead to getting '0' again for some devices. What should I do?
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
gameSelectionLayout();
}
}, 100);