Get the width / height of the width or font width / height / other sizes before the first display

I know that performing size size calculations for placement is incredulous. Android layout managers must correctly place all views. However, there are some legitimate cases where some kind of calculation needs to be done to provide hints (for example, the number of columns in a GridView or the size of a text view to allow the minimum number of characters displayed per line). For these cases, I would like to get relevant information about the width / height of the view or the font width / height / etc. However, calls to getWidth () / getHeigth () / etc never return a valid value if the view was not displayed, but then it is too late. This is the situation with catch-22. I wonder if there is some way that I have not found (android api is great to understand everything in my mind), which does what I described above is possible.

+4
source share
2 answers

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

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

+7
source

Yes, I tested the proposal 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 do not understand is how I skipped this! :) I knew everything about the measurement process, but I was stuck in using it in custom views ...

+5
source

All Articles