Skip to content
Advertisement

How to covert vw measurement to dp in android?

Android Studio Code Snippet

I have an android device that has it’s maximum width and height specified in dp units.

  • Max Width – 1079 dp
  • Max Height – 399 dp

I want to create a LinearLayout that has to be present vertically and horizontally centered with its height to be in wrap_content length and width to occupy 50vw units. I know 50vw means occupying 50% size of the width, but I am having a hard time converting this 50vw width requirement into dp dimension. So should I hardcode the layout width to be 399/2 dp = 199.5dp, which should be equal to 50vw? Or am I correct in simply dividing the max width of the device in half to match the 50vw requirement?

JavaScript

Please let me know if my understanding is incorrect? Thanks.

Advertisement

Answer

If you are using LinearLayout and you want the width to 50% of parent, you can use orientation="horizontal", weightSum, layout_weight. Here is an example

JavaScript

If you use ConstraintLayout you can also set the width to 50% of parent width by using Guideline with percent, or layout_constraintHorizontal_weight

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement