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.