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?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="199.5dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Hello World!"
            android:textAlignment="center" />
    </LinearLayout>

</LinearLayout>

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        android:background="#f00" />

</LinearLayout>

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

Advertisement