Home > front end >  Why are 30 x (1dp 5dp) not 180dp?
Why are 30 x (1dp 5dp) not 180dp?

Time:01-26

I am working on a timeline for a timespan of 30 minutes. So I put 30 LinearLayouts(horizontal) with each one 1dp wide View which is colored and one 5dp wide View for the distance to the next tick(colored View). I am very very very sure each LinearLayout got layout_width set to 6dp. So I assume I have a total width of 180dp but as you can see it does not fit into a 180dp wide Container View (ConstraintLayout). The ConstraintLayout has to be exactly 185dp wide.

I first thought it is a display issue in the editor, but it is the same on my phone.

When I select another display in the editor (e.g. Pixel 2 XL with 560dpi) 30 x 6dp fits in 180dp. With a Pixel 3a with 440dpi I have this issue.

Why is this happening?

View in Android Studio View Editor

View in Android Studio View Editor

CodePudding user response:

dp is a floating point unit but for rendering purposes it gets rounded to an integer.

Pixel 2 XL has 3.5x xxxhdpi density so 6dp is 21px on screen.

Pixel 3a has 2.75 xxhdpi density so 6dp is 16.5px that gets rounded to 17px.

If you'd use a mod 4 or mod 8 pixel grid you wouldn't have rounding errors like this. That is, make your dp sizes multiples of 4 (or 8) dp.

If you want to have the 6dp there, for this kind of purpose I'd probably make a custom view that does the required computation internally without using separate views for each bit, causing the views to snap to pixel grid.

  •  Tags:  
  • Related