I have a view made up of TableLayout, TableRow and TextView
. I want it to look like a grid. I need to get the height and width of this grid. The methods getHeight()
and getWidth()
always return 0. This happens when I format the grid dynamically and also when I use an XML version.
How to retrieve the dimensions for a view?
Here is my test program I used in Debug to check the results:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TextView;
public class appwig extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindemo); //<- includes the grid called "board"
int vh = 0;
int vw = 0;
//Test-1 used the xml layout (which is displayed on the screen):
TableLayout tl = (TableLayout) findViewById(R.id.board);
tl = (TableLayout) findViewById(R.id.board);
vh = tl.getHeight(); //<- getHeight returned 0, Why?
vw = tl.getWidth(); //<- getWidth returned 0, Why?
//Test-2 used a simple dynamically generated view:
TextView tv = new TextView(this);
tv.setHeight(20);
tv.setWidth(20);
vh = tv.getHeight(); //<- getHeight returned 0, Why?
vw = tv.getWidth(); //<- getWidth returned 0, Why?
} //eof method
} //eof class
getHeight()
andgetWidth()
after the Activity lifecycle has asked the views to measure themselves, in other words, do this kind of stuff inonResume()
and that's it. You shouldn't expect a not-yet-laid-out object to know its dimensions, that's the whole trick. No need for the magic suggested below. – LilyliveredgetHeight()/Width()
inonResume()
did not yield > 0 value for me. – Cassity