Get view width/height or font width/height/other sizes before first display

ⅰ亾dé卋堺 提交于 2020-01-10 02:12:25

问题


I know that doing view size calculations for placement is frowned up. Android layout managers should place all views properly. However there are some legitimate cases when some sort of calculations should be done in order to provide hints (ex. number of columns in a GridView or sizing a text view to allow a minimum number of characters displayed in a line). For these cases I would like to get the relevant view width/height info or font width/height/etc. However the getWidth()/getHeigth()/etc calls never return a valid value unless the view has been rendered on display but then it is late. It is a catch-22 situation. I wonder if there is some way that I haven't found (the android api is big to comprehend all in my mind) that makes what I have described above possible.


回答1:


The size of view cannot be calculated until its parent is calculated, but you can always force this calculation by calling measure(allowedWidth, allowedHeight) on it. Then getMeasuredWidth() will works.

see http://developer.android.com/reference/android/view/View.html#measure(int, int)




回答2:


Yep I tested the suggestion and it works !

Sample code.

Display display = getWindowManager().getDefaultDisplay();
View s = findViewById(R.id.Screen); // Screen is a container layout
s.measure(display.getWidth(), display.getHeight());
View c = findViewById(R.id.Cell0);
Log.i(TAG, "cell width = " + String.valueOf(c.getMeasuredWidth())
  +  " height = " + String.valueOf(c.getMeasuredHeight()));

What I don't understand is how I missed this ! :) I knew all about the measuring process but I had stuck in its use in custom views ...



来源:https://stackoverflow.com/questions/5375631/get-view-width-height-or-font-width-height-other-sizes-before-first-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!