Dynamically calculate size of View elements [duplicate]
I have a unknown number of TextView elements some EditText elements and so on, that are all placed in one linear layo开发者_如何学Gout... 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
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
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.
精彩评论