I tested a simple layout on different densities. Here's the layout xml code for activity_main.xml
:
<RelativeLayout 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"
android:padding="32dp"
tools:context="com.noah.densitytest.MainActivity"
android:background="@color/gray" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:padding="4dp"
android:background="#000000" >
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="16sp"
android:layout_marginTop="32dp"
android:background="@color/algea_green" />
<View
android:id="@+id/square_top"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginLeft="16dp"
android:layout_toRightOf="@id/tv1"
android:background="@color/aqua" />
<View
android:id="@+id/square_center"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_centerInParent="true"
android:layout_marginRight="32dp"
android:background="@color/blue" />
<View
android:layout_width="32dp"
android:layout_height="256dp"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/square_center"
android:background="@color/dark_slate_blue" />
<View
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_toRightOf="@id/square_top"
android:layout_marginLeft="48dp"
android:layout_marginTop="128dp"
android:background="@color/medium_purple" />
</RelativeLayout>
</RelativeLayout>
I just put it in a single folder - res/layout.
I used dp which is said to be density independent and that Android will automatically scale values given in this unit. However, the problem is that the layout appears differently per density. I used mdpi, hdpi, xhdpi, and xxhdpi AVDs. But all the other attributes are 8in, 1280x720, normal, long - across all test devices. So why is it that they appear differently? It really looks very ugly on the other densities. I also tried copying it to specific folders like layout-mdpi, layout-hdpi, etc but still the same result.
However, if I use px as the unit, then the layout on all devices look the same. Why does it seem better using px?
I hope you could explain this to me or can provide me good links where I could deeply understand how Android does this and why dp is more recommended than px which is in constrast to this result.
Here's what the result looked like: