1

I am trying to get the height and width of a table layout and use that to set the height and width of my buttons. I use the following code to achieve this:

ViewGroup.LayoutParams params = new TableLayout.LayoutParams();
params.width = params.width/3;
params.height = params.width;

The code however does not work and I am unsure as of to why.

Umair
  • 6,366
  • 15
  • 42
  • 50
Popolok11
  • 57
  • 9
  • are you facing any error or an exception ? – Umair Jun 21 '18 at 11:02
  • Maybe the answer is here? https://stackoverflow.com/questions/21926644/get-height-and-width-of-a-layout-programmatically – John T Jun 21 '18 at 11:05
  • Are you setting the params to the view? like `view.setLayoutParams(params)` also you have not defined `width` and `height` parameters in layout params therefore it would be `0/3` and `0` – HawkPriest Jun 21 '18 at 11:06

2 Answers2

4

You're using the same params Object which are also empty. Your code should be like this

ViewGroup.LayoutParams btnParams = btn.getLayoutParams();

ViewGroup.LayoutParams params = tableLayout.getLayoutParams();
btnParams.width = params.width/3;
btnParams.height = params.width;
btn.setLayoutParams(btnParams)
Niza Siwale
  • 2,390
  • 1
  • 18
  • 20
1

when onCreate is executed in your Activity, the UI has not been drawn to the screen yet, so nothing has dimensions yet since they haven't been laid out on the screen. When setContentView is called, a message is posted to the UI thread to draw the UI for your layout, but will happen in the future after onCreate finishes executing. Posting a Runnable to the UI thread will put the Runnable at the end of the message queue for the UI thread, so will be executed after the screen has been drawn,thus everything has dimensions. (that's why you got a NullPointerException from Niza Siwale answer)

btn.post(new Runnable() {
        @Override
        public void run() {
            TableLayout myTableLayout = findViewById(R.id.idOfTheTableLayout);
            int width = myTableLayout.getWidth();
            int height = myTableLaout.getHeight();

            ViewGroup.LayoutParams params = btn.getLayoutParams();
            params.height = height;
            params.width = width;
            btn.setLayoutParams(params);
        }
}

hope it works.

user 007
  • 821
  • 10
  • 31
  • What is a Runnable and how do I use it? – Popolok11 Jun 21 '18 at 11:48
  • after initializing your button in the onCreate method (Button btn = findViewById(R.id.btnId)) you can then use the code I posted (inside the onCreate method). As I mentioned in my explanation Runnable is used to separate your code. That way you make sure to get the width and hight only after the screen was drawn. Otherwise you always trying to get the dimensions of a null object because it wasn't initialized yet. – user 007 Jun 21 '18 at 11:57
  • Thank you, this worked great! – Popolok11 Jun 21 '18 at 12:23