3

I have a unknown number of TextView elements some EditText elements and so on, that are all placed in one linear layout... And I want to calculate the height of the layout at run time so I can get the exact size in pixels for different resolution screens. Some editboxes can contain more text then other so their size will be bigger... Is there possibility to calculate the size of a layout at runtime ?

Thanks

skaffman
  • 398,947
  • 96
  • 818
  • 769
Lukap
  • 31,523
  • 64
  • 157
  • 244

2 Answers2

3

To get height of layout you have to write the code in onWindowFocusChanged() method. First get the layout in onCreate() method then write the following code.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
    System.out.println("...111Height..."+mainLayout.getMeasuredHeight());
}

Thanks Deepak

Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
  • tnx, not just in onWindowFocusChanged it is possible to get the size of the layout in other places like onclicklisteners. – Lukap May 31 '11 at 15:02
  • One should not need to rely on focus to obtain the size of an element. As long as the code asking for the measured size occurs post measure, it should be fine. – Ameen Apr 16 '13 at 20:34
0

You can get the current width of a view by giving:

String s = tv.getText().toString(); //tv is my textview name
float currentWidth = tv.getPaint().measureText(s);

To get the phone density, give:

float phoneDensity = this.getResources().getDisplayMetrics().density;

When you do currentWidth * phoneDensity you get the width based upon your device.

Anju
  • 9,379
  • 14
  • 55
  • 94
  • Thanks this is very cool solution. unfortunately this can solve only part of my problem. I need the size of the whole view including the margins, padding and so on. . . I am not sure if there is a solution that why I asked :) – Lukap May 31 '11 at 12:40