开发者

Dynamically calculate size of View elements [duplicate]

This question already has answers here: Determining the size of an Android view at runtime (13 answers) Closed 9 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜