0

I’m trying to calculate the width and height of child Layouts/Views based on the dimensions of the ViewGroup that contains them.

I’m trying to factor in each childs’s margin value, but cannot seem to get this quite right.

I’ve tried every conversion under the sun (dip, sp, px, in, mm), but still come to the same conclusion, which is that margin values get converted to a much smaller pixel value than any of the other dimensional values (ie, width & height).

I need this conversion factor. I’ve tried many things to calculate it (Context.Resources.DisplayMetrics - Density, DensityDpi, ScaledDensity), but haven’t been successful.

I don't believe that this conversion factor can be taken or derived from any values available at runtime, and so was wondering if maybe someone knew what it was (or maybe where to find or calculate it).


To give some context, I'm implementing a custom calendar which contains a 5x7 grid of child-layout's (LinearLists), where each child has margins surrounding them.

The outer-most view is a RelativeLayout, which has a width and height of W and H respectively, and the margin width is M. Therefore, you'd think that

CELL_WIDTH = W/7 - M*7
CELL_HEIGHT = H/5 - M*5

However the margin width factors M*7 and M*5 end up being much too large, causing the overall grid to be smaller than the parent view (which is a problem, b/c I need to fill it).

I've tried a ton of different conversion techniques from posts here and elsewhere with no success. I'm convinced that there is some conversion factor that android uses to internally store the margin values (which I'm assuming is in pixels). It is this conversion factor I'm after (unless of course someone knows of a better/correct way to perform the calculation that I'm attempting here).

Here are the links I've tried, and I even converted one of the Java solutions to C# and am currently using it (though it did not solve this particular problem for me, it helped to shed a lot of light on it, and is helping elsewhere):

How to parse a dimension string and convert it to a dimension value

Community
  • 1
  • 1
samus
  • 6,102
  • 6
  • 31
  • 69
  • I suppose a quick fix would be to render a view with margins, then take measurements of it afterwards and take a ration of the specified width (without margins) and the measured width (with margins). However, this would be a pain to have to work into all of my custom classes, and its gross :{ – samus Oct 03 '12 at 21:25

1 Answers1

0

Oh my God I'm an idiot!

I've been tooling around for so long that I wasn't even considering the equation as being flawed.

For each cell size, I should only shave off 1 margin width/height, not all of them, which the current equation is doing.

So, the correct equations are:

CELL_WIDTH = W/7 - M 
CELL_HEIGHT = H/5 - M

Ugh, I feel silly.

samus
  • 6,102
  • 6
  • 31
  • 69