1

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);
Community
  • 1
  • 1
Sundeep
  • 23,246
  • 2
  • 28
  • 103

1 Answers1

0

Got answer through Google Helpouts The solution neither uses ViewTreeObserver nor delayed execution, but WindowManager (didn't know about this one). The code is given below:

    WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    Point size = new Point();
    if(Build.VERSION.SDK_INT >= 13)
        display.getSize(size);
    else
    {
        size.x = display.getWidth();
        size.y = display.getHeight();
    }
    screen_width = size.x;
    screen_height = size.y;
Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • So this gets the entire screen height and width, right? Why not use `int screenWidth = getResources().getDisplayMetrics().widthPixels;`? – SMBiggs Jul 05 '18 at 22:44
  • @ScottBiggs this was around Android version 4 and 5.. I dunno what's the current way of doing it.. – Sundeep Jul 06 '18 at 02:17