我在不同的密度下测试了一个简单的布局。以下是activity_main.xml
的布局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>
我只把它放在一个单独的文件夹 - res/layout 中。我使用了dp,这被称为密度无关单位,并且Android会自动缩放给定的值。然而,问题在于布局在每个密度下显示不同。我使用了mdpi、hdpi、xhdpi和xxhdpi AVD。但是所有其他属性都是8英寸、1280x720、normal、long - 在所有测试设备上都是如此。那么为什么它们看起来不同呢?在其他密度下看起来非常丑陋。我还尝试将其复制到特定的文件夹中,如layout-mdpi、layout-hdpi等,但结果仍然相同。然而,如果我使用像素作为单位,那么所有设备上的布局看起来都一样。为什么使用像素似乎更好呢?
希望您能向我解释这个问题,或者提供给我一些好的链接,让我深入了解Android是如何做到这一点的,以及为什么推荐使用dp而不是像素,因为这与结果相反。
以下是结果的外观:
layout-small
、layout-normal
等)或更灵活的“最小宽度”限定符(layout-sw600dp
、layout-sw720dp
等)。您可以在答案中的第一个链接中了解更多信息。至于@dimens
,可能您想要将尺寸缩小而不是放大,以适应更高的密度,尽管这有点违背了初衷。 - Andrew T.